我想知道为什么C ++的使用前声明规则不包含在类内。
I'm wondering why the declare-before-use rule of C++ doesn't hold inside a class.
看这个例子:
#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,则代码有效。
If BASE is defined, the code is valid.
在A的构造函数中,我可以使用尚未声明的B :: foo。
Within A's constructor I can use B::foo, which hasn't been declared yet.
这为什么起作用,并且在大多数情况下,为什么只能起作用内部一个类?
Why does this work and, mostly, why only works inside a class?
推荐答案这是因为成员函数仅在整个类定义都被编译后才编译即使函数定义是内联编写的,也可以由编译器解析,而常规函数则在读取后立即编译。 C ++标准要求这种行为。
That's because member functions are compiled only after the whole class definition has been parsed by the compiler, even when the function definition is written inline, whereas regular functions are compiled immediatedly after being read. The C++ standard requires this behaviour.
更多推荐
为什么类中不需要“使用前声明”规则?
发布评论