我们可以在 C++ 中的主程序之后定义 struct 吗?定义函数时,可以在main程序之前声明函数,然后在main函数之后写函数定义。我想知道我们在定义结构时是否可以做类似的事情。谢谢你。
我们可以在 C++ 中的主程序之后定义 struct 吗?
我想你的意思是main
函数。是的,我们可以在main
函数之后定义类(包括结构体)。一个演示:
int main(){}
struct S{};
定义函数时,可以在主程序之前声明函数,然后在主程序之后编写函数定义。我想知道我们在定义结构时是否可以做类似的事情。
同样适用于类,您可以(向前)在函数之前声明它们,并在之后定义。但是,不完整(已声明但未定义)类的使用非常有限。您可以定义指针和对它们的引用,但不能创建它们或调用任何成员函数。一个演示:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句