为什么类中不需要“使用前声明”规则? [英] Why is the 'Declare before use' rule not required inside a class?

查看:118
本文介绍了为什么类中不需要“使用前声明”规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么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.

这篇关于为什么类中不需要“使用前声明”规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆