在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/