问题描述
我很清楚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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)