我正在尝试创建一个类原型(prototype),但我不断收到错误消息:“aClass”使用未定义的类“myClass”
我很确定我正在正确制作原型(prototype)。使用原型(prototype)函数有效,但类原型(prototype)无效。
extern class myClass; // prototypes
extern void myFunction();
int main() // main
{
myClass aClass;
myFunction();
return 0;
}
class myClass { // this doesn't work
public:
void doSomething() {
return;
}
myClass() {};
};
void myFunction() { // this works
return;
}
最佳答案
myClass aClass;
是一个定义,要求myClass
是一个complete type ; myClass
的大小和布局必须在编译时已知。
Any of the following contexts requires class T to be complete:
- ...
- definition of an object of type T;
- ...
这意味着必须在此之前定义类。
请注意,前向声明适用于不需要类型完整的情况,例如类型指针的定义(如 myClass* p;
)。
对于函数来说,情况就不同了。函数是 odr-used如果对其进行函数调用,则其定义必须存在于某处。请注意,在编译时不需要定义,在 main()
之后定义它(之前有声明)就可以了。
a function is odr-used if a function call to it is made or its address is taken. If an object or a function is odr-used, its definition must exist somewhere in the program; a violation of that is a link-time error.
顺便说一句:在类的前向声明中使用 extern
是多余的。
关于C++ 类原型(prototype)无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47425927/