混合类和结构

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.

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

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

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)