在C ++中声明之前使用 [英] Declare before use in C++

查看:124
本文介绍了在C ++中声明之前使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

为什么这个工作,

推荐答案

这是因为成员函数只有在整个类定义之后才被编译由编译器解析,即使函数定义是内联编写的,而正则函数在读取后立即编译。 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.

这篇关于在C ++中声明之前使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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