c++ - 我们可以在 C++ 的 main 函数之后定义结构吗?

标签 c++ struct

在C++中可以在主程序之后定义struct吗?我们在定义函数的时候,可以在主程序之前声明函数,然后在主函数之后写函数定义。我想知道我们是否可以在定义结构时做类似的事情。谢谢。

最佳答案

Can we define struct after the main program in C++?

我假设您指的是 main 函数。是的,我们可以在 main 函数之后定义类(包括结构)。演示:

int main(){}
struct S{};

When we define functions, we can declare the function before the main program and then write the function definition after the main program. I wanted to know if we can do something similar to this when defining structures.

这同样适用于类,您可以(向前)在函数之前声明它们,并在之后定义。但是,不完整(已声明但未定义)类的使用非常有限。您可以定义指针和对它们的引用,但不能创建它们或调用任何成员函数。演示:

struct S;     // (forward) declaration of a class
S* factory(); // (forward) declaration of a function
int main(){
    S* s = factory(); // OK, no definition required
    // s->foo();      // not OK, S is incomplete
    // S s2;          // not OK
}
struct S{             // definition of a class
    void foo();       // declaration of a member function
};
S* factory() {
     static S s;      // OK, S is complete
     s.foo();         // OK, note how the member function can be called
                      // before it is defined, just like free functions
     return &s;
}
void S::foo() {}      // definition of a member function

关于c++ - 我们可以在 C++ 的 main 函数之后定义结构吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42527464/

相关文章:

c - 访问返回指针时出现段错误

C - 指向结构体 "Segmentation fault (core dumped)"中的动态数组的指针

c# - 将具有另一个结构数组的结构从 C# 传递到 C (P/Invoke)

c++ - 在 Visual Studio 2017 中调试 C++ 应用程序进入的不是我的代码,有没有办法关闭它?

c++ - 为什么我的角落小部件没有显示在 QTabWidget 中?

C++ Qt : Check the current State of QStateMachine

c++ - 类中的公共(public)结构

c++ - 带指针的结构的大小

c++ - operator << - 如何检测最后一个参数

c++ - 使用Nsight调试导出DLL的非启动项目中的CUDA代码