<分区>
Possible Duplicate:
Why compiler doesn't allow std::string inside union ?
当我开始使用 C++ 时,我知道我遇到了这个问题:编译器不允许我将 std::string
类型的变量放入 union 中。
那是几年前的事了,但实际上我仍然不知道确切的答案。我读了一些与复制函数相关的内容,其中包含 union 不喜欢的字符串,但仅此而已。
- 为什么 C++ STL 字符串与 union 不兼容?
<分区>
Possible Duplicate:
Why compiler doesn't allow std::string inside union ?
当我开始使用 C++ 时,我知道我遇到了这个问题:编译器不允许我将 std::string
类型的变量放入 union 中。
那是几年前的事了,但实际上我仍然不知道确切的答案。我读了一些与复制函数相关的内容,其中包含 union 不喜欢的字符串,但仅此而已。
最佳答案
来自 Wikipedia :
C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator. In particular, it is impossible to have the standard C++ string as a member of a union.
这样想:如果你有一个像 std::string
这样的类类型和一个原始类型(比如 long
)的 union ,怎么会编译器知道您何时使用类类型(在这种情况下需要调用构造函数/析构函数)以及何时使用简单类型?这就是为什么成熟的类类型不允许作为 union 的成员。
关于c++ - 为什么 std::string 与 C union 不兼容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474158/