Strange Behaviour Class Objects Inside Union

前端 未结 3 1263
情歌与酒
情歌与酒 2020-12-29 14:30

Hi I wanted know the reasons of the following code

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

  class test1
  {
    public:         


        
3条回答
  •  渐次进展
    2020-12-29 15:05

    The C++ standard puts certain restrictions on the types of data which can be placed inside of a union. In 9.5.1 the standard reads:

    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.

    So your program doesn't work because you explicitly define a constructor, and therefore your object violates the non-trivial constructor restriction.

提交回复
热议问题