我很清楚class 和 struct 之间的区别,但是我很难权威地说这是否定义明确:
I'm well aware of the difference between class and struct, however I'm struggling to authoritatively say if this is well defined:
// declare foo (struct)
struct foo;
// define foo (class)
class foo {
};
// instance of foo, claiming to be a struct again! Well defined?
struct foo bar;
// mixing class and struct like this upsets at least one compiler (names are mangled differently)
const foo& test() {
return bar;
}
int main() {
test();
return 0;
}
如果这是未定义的行为,有人可以指出我权威(即 ISO 中的章节和诗句)参考的方向吗?
If this is undefined behaviour can someone point me in the direction of an authoritative (i.e. chapter and verse from ISO) reference?
编译器在处理此问题时遇到问题(Carbide 2.7)相对较旧,我尝试过的所有其他编译器都对此非常满意,但显然这并不能证明任何事情.
The compiler with problems handling this (Carbide 2.7) is relatively old and all the other compilers I've tried it on are perfectly happy with this, but clearly that doesn't prove anything.
我的直觉是这应该是未定义的行为,但我找不到任何可以证实这一点的东西,我很惊讶 GCC 版本或 Comeau 已经警告过了.
My intuition was this ought to be undefined behaviour but I can't find anything to confirm this and I'm surprised that none of the GCC versions or Comeau so much as warned about it.
在我看来,它像是已定义的行为.特别是,§9.1/2 说:
It looks to me like it's defined behavior. In particular, §9.1/2 says:
仅由 class-key identifier ; 组成的声明要么是对当前作用域中的名称或标识符的前向声明作为类名.它将类名引入当前作用域.
A declaration consisting solely of
class-key identifier ;is either a redeclaration of the name in the current scope or a forward declaration of the identifier as a class name. It introduces the class name into the current scope.
标准在定义一个类时区分使用class、struct或union,但在这里,谈论关于声明,没有这样的区别——使用一个 class-key 等同于任何其他.
The standard distinguishes between using class, struct or union when defining a class, but here, talking about a declaration, no such distinction is made -- using one class-key is equivalent to any other.
这篇关于混合类和结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
如何在 C++ 中读取和操作 CSV 文件数据?How can I read and manipulate CSV file data in C++?(如何在 C++ 中读取和操作 CSV 文件数据?)
在 C++ 中,为什么我不能像这样编写 for() 循环:In C++ why can#39;t I write a for() loop like this: for( int i = 1, double i2 = 0; (在 C++ 中,为什么我不能像这样编写 for() 循环: for(
OpenMP 如何处理嵌套循环?How does OpenMP handle nested loops?(OpenMP 如何处理嵌套循环?)
在循环 C++ 中重用线程Reusing thread in loop c++(在循环 C++ 中重用线程)
需要精确的线程睡眠.最大 1ms 误差Precise thread sleep needed. Max 1ms error(需要精确的线程睡眠.最大 1ms 误差)
是否需要“do {...} while ()"?环形?Is there ever a need for a quot;do {...} while ( )quot; loop?(是否需要“do {...} while ()?环形?)