c – 为什么在课堂内不需要“在使用前声明”规则?
作者:互联网
参见英文答案 > Do class functions/variables have to be declared before being used? 4个
我想知道为什么C之前的声明使用规则不能保持在类中.
看看这个例子:
#ifdef BASE
struct Base {
#endif
struct B;
struct A {
B *b;
A(){ b->foo(); }
};
struct B {
void foo() {}
};
#ifdef BASE
};
#endif
int main( ) { return 0; }
如果定义了BASE,则代码有效.
在A的构造函数中,我可以使用尚未声明的B :: foo.
为什么这有效,而且大多数情况下,为什么只能在课堂上工作?
解决方法:
这是因为只有在编译器解析了整个类定义之后才编译成员函数,即使函数定义是内联编写的,而常规函数在读取后立即编译. C标准需要这种行为.
标签:c,class,forward-declaration 来源: https://codeday.me/bug/20191002/1843254.html