2016-03-07 69 views
-1

的成員我haee這一小段代碼中,我想創建一個struct員工。員工可以是經理或工人。我無法訪問工會成員。這裏是我的代碼C++ - 不能夠訪問一個聯盟

#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 

我不知道我在做什麼錯。請幫忙 謝謝SO

+0

'的std :: string'不能在C++ 03的結合。在C++ 11 – Jarod42

+0

無限制聯盟將需要'Person'構造。 – Jarod42

+0

爲什麼不能串聯? –

回答

2

您的聯合中不能有非POD對象,但可以有一個指向非PDO對象的指針(因此string*有效)。

What are POD types in C++?

Pehaps一個const char*就夠了,如果你需要的是訪問這些字符串字面量「銷售」 &「營銷」 -

0

順便說一句 - 你的數據模型是完全錯誤的。您不應該使用需要使用類層次結構的聯合。

你需要一個基類員工,以及派生類經理。

struct Employee { 
    int id; 
    string department; 
}; 

struct Manager : public Employee 
{ 
    int level; 
} 

和不使用結構採用類

,並有更好的成員命名。像m_company或company_

和不使用命名空間std做,說的std :: string等

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

class Manager : public Employee 
{ 
    int _level; 
}