为什么C ++不允许匿名结构和联合? [英] Why does C++ disallow anonymous structs and unions?

查看:311
本文介绍了为什么C ++不允许匿名结构和联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些C ++编译器允许匿名联合和结构作为标准C ++的扩展。

Some C++ compilers permit anonymous unions and structs as an extension to standard C++. It's a bit of syntactic sugar that's occasionally very helpful.

有什么理由阻止这种做法成为标准的一部分?是否有技术障碍?哲学的?

What's the rationale that prevents this from being part of the standard? Is there a technical roadblock? A philosophical one? Or just not enough of a need to justify it?

这里是我所说的一个例子:

Here's a sample of what I'm talking about:

struct vector3 {
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float v[3];
  };
};



我的编译器会接受这个,但它警告,无组织结构/联合是C ++的非标准扩展

推荐答案

由于其他人指出,标准C ++中允许使用匿名联合,但匿名结构不允许。

As others have pointed out anonymous unions are permitted in standard C++, but anonymous structs are not.

这样做的原因是C支持匿名联合而不是匿名structs *,所以C ++支持前者兼容性,但不支持后者,因为它不需要兼容性。

The reason for this is that C supports anonymous unions but not anonymous structs*, so C++ supports the former for compatibility but not the latter because it's not needed for compatibility.

此外,C ++中的匿名结构没有太多用处。使用你演示,有一个结构包含三个浮动可以引用 .v [i] .x .y .z ,我相信结果在C ++中未定义的行为。 C ++不允许您写入联合的一个成员,例如 .v [1] ,然后从另一个成员读取,例如 .y 。虽然这样做的代码并不罕见,但实际上并没有很好定义。

Furthermore, there's not much use to anonymous structs in C++. The use you demonstrate, to have a struct containing three floats which can be referred to either by .v[i], or .x, .y, and .z, I believe results in undefined behavior in C++. C++ does not allow you to write to one member of a union, say .v[1], and then read from another member, say .y. Although code that does this is not uncommon it is not actually well defined.

C ++的用户定义类型的设施提供了替代解决方案。例如:

C++'s facilities for user-defined types provide alternative solutions. For example:

struct vector3 {
  float v[3];
  float &operator[] (int i) { return v[i]; }
  float &x() { return v[0]; }
  float &y() { return v[1]; }
  float &z() { return v[2]; }
};

* C11显然添加了匿名结构,所以未来的C ++版本可能会添加它们。 / sub>

* C11 apparently adds anonymous structs, so a future revision to C++ may add them.

这篇关于为什么C ++不允许匿名结构和联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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