混合类和结构体 [英] Mixing class and struct

查看:127
本文介绍了混合类和结构体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚类和结构之间的区别,但我努力授权说如果这是很好定义:

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?

编译器在处理此问题时遇到问题(硬质合金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版本或

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:


一个只包含类键标识符的声明; 是当前作用域中
名称的重新声明,或者标识符作为类名的前向声明。它将类名引入当前范围。

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.

这篇关于混合类和结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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