混合类和结构

Mixing class and struct(混合类和结构)
本文介绍了混合类和结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我很清楚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.

标准在定义一个类时区分使用classstructunion,但在这里,谈论关于声明,没有这样的区别——使用一个 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)