gpt4 book ai didi

c++ - Union 内部的奇怪行为类对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:17 27 4
gpt4 key购买 nike

您好,我想知道以下代码的原因

void main()
{
class test
{
public:
test(){}
int k;
};

class test1
{
public:
test1(){}
int k;
};

union Test
{
test t1;
test1 t2;
};
}

对于上面的代码,它给出了错误“error C2620: union 'Test' : member 't1' has user-defined constructor or non-trivial default constructor

class test
{
public:
//test(){}
int k;
};

class test1
{
public:
//test()1{};
int k;
};

union Test
{
test t1;
test1 t2;
};

对于上述,没有错误。

我想知道原因。

在此先感谢您。 :)

最佳答案

根据 C++ 标准(§9.5.1,在其他答案中也有引用):

A union can have member functions (including constructors and destructors), but not virtual functions. A union shall not have base classes. A union shall not be used as a base class. An object of a class with a non-trivial constructor, a non-trivial copy-constructor, a non-trivial destructor, or a non-trivial copy assignment operator cannot be a member of a union, nor can an array of such objects. If a union contains a static data member, or a member of a reference type, the program is ill-formed.

我首先链接到 Wikipedia article about POD types其中指出:

A POD type in C++ is defined as either a scalar type or a POD class. POD class has no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no bases and no virtual functions. The standard includes statements about how PODs must behave in C++.

In certain contexts, C++ allows only POD types to be used. For example, a union in C++ cannot contain a class that has virtual functions, or nontrivial constructors or destructors. This restriction is imposed because the compiler cannot know which constructor or destructor should be called for a union.

第二段的第一句话可能会让您认为 C++ 只允许 POD 类型成为 union 的一部分。事实并非如此,因为它允许具有私有(private)成员的类成为 union 的一部分:

#include <iostream>
using namespace std;

class test1
{
int i;
};

class test2
{
int i;
};

union test
{
test1 t1;
test2 t2;
};

int main()
{
cout << __is_pod(test1) << endl;
cout << __is_pod(test2) << endl;
cout << __is_pod(test) << endl;

return 0;
}

上面用MSVC++编译的程序打印出来:

0
0
1

关于c++ - Union 内部的奇怪行为类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1873219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com