无法访问联盟成员

时间:2016-03-07 23:00:35

标签: c++ structure unions

我在这一小段代码中试图创建一个struct Employee。员工可以是经理或工人。我无法访问工会成员。这是我的代码

#include <iostream>
#include <string>
using namespace std;

struct Employee {
 int id;
 union Person {
  struct Manager {
   int level;
  } manager;
  struct Worker {
   string department;
  } worker;
 } company[3];
};


int main() {
 Employee one;
 one.id = 101;
 one.company[0].manager.level = 3;

 Employee two;
 two.id = 102;
 two.company[1].worker.department = "Sales";

 Employee three;
 three.id = 103;
 three.company[2].worker.department = "Marketing";
}

我得到的错误是

arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with constructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with destructor not allowed in union
arraOfUnions.cc:13:5: error: member 'Employee::Person::Worker Employee::Person::worker' with copy assignment operator not allowed in union
arraOfUnions.cc:13:5: note: unrestricted unions only available with -std=c++0x or -std=gnu++0x

我不确定我做错了什么。请帮忙 谢谢你

2 个答案:

答案 0 :(得分:2)

你的联盟中不能有非POD对象,但你可以有一个指向非PDO对象的指针(因此string*有效)。

What are POD types in C++?

Pehaps a const char*就足够了,如果您只需要访问那些字符串文字“Sales”&amp; “市场营销” -

答案 1 :(得分:0)

BTW - 您的数据模型完全错误。您不应该使用需要使用类层次结构的联合。

您需要一个基类Employee和一个派生类Manager。

struct Employee {
   int id;
  string department;
};

struct Manager : public Employee
{
  int level;
}

并且不要使用struct use class

并为成员提供更好的命名。比如m_company或company _

并且不要使用命名空间std,比如说std :: string等

class Employee {
   int _id;
  std::string _department;
};

class Manager : public Employee
{
  int _level;
}