为什么类中不需要“使用前声明”规则?

编程入门 行业动态 更新时间:2024-10-12 18:15:40
本文介绍了为什么类中不需要“使用前声明”规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

为什么类中不需要“使用前声明”规则?

本文发布于:2023-11-02 00:30:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1550853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不需要   类中   声明   规则

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!