2012-12-03 36 views
2

我在创建一个标准向量形式的类。我一直在用一些实现了集合而不是向量的类来编写一些程序,所以我有点困惑。C++调用向量类中的私有数据成员

这里是我的类:

class Employee 
{ 

private: 

    Struct Data 
    { 
unsigned Identification_Number; 
// Current capacity of the set 

unsigned Department_Code; 
// Department Code of employee 

unsigned Salary; 
// Salary of employee 

str Name; 
// Name of employee 
    } 

如果我要调用私有数据成员以后,可以只是我下面?

vector<Employee> Example; 

//Assume there's data in Example 

cout << Example[0].Identification_Number; 
cout << Example[3].Salary; 

如果不是,那么apprpriate容器是什么?列表清单是否更适合处理这组数据?

+1

为什么要将'struct'私有化,当你想公开可用?或者是'Struct Data {'错字? – Cornstalks

+2

为什么即使有'Data'结构呢?为什么不直接将所有'Data'的成员放在Employee类中? –

+0

这里的容器是完全不相关的,你似乎完全不知道如何访问私人会员。当然,答案是,你不会想;这就是整个问题。 – GManNickG

回答

1

这是不可能的,你提供原样,但有一些修改,你可以把它的工作代码:

class Employee 
{ 
public: 
    unsigned GetID() const    { return Identification_Number; } 
    unsigned GetDepartment() const  { return Department_Code; } 
    unsigned GetSalary() const   { return Salary; } 
    // Assuming you're using std::string for strings 
    const std::string& GetString() const { return string; } 
private: 
    unsigned Identification_Number; // Current capacity of the set 
    unsigned Department_Code;  // Department Code of employee 
    unsigned Salary;    // Salary of employee 
    string Name;     // Name of employee 
}; 

注意,Data结构是完全多余的在这种情况下,你已经呈现。我刚刚将Employee类中的所有数据成员都放置为encapsulation的私有数据成员。

然后你就可以访问他们这样说:

std::vector<Employee> Example; //Assume there's data in Example 
// ... 
cout << Example[0].GetID(); 
cout << Example[3].GetSalary(); 

想必您将设置Employee类中他们正确的价值观单个变量莫名其妙。

0

的常见方式是访问函数:

#include <iostream> 

class Employee 
{ 
public: 
    void setID(unsigned id) 
    { 
     Identificaiton_Number = id; 
    } 

    unsigned getID() 
    { 
     return Identificaiton_Number; 
    } 

private: 
    unsigned Identification_Number; 
    // Current capacity of the set 

    unsigned Department_Code; 
    // Department Code of employee 

    unsigned Salary; 
    // Salary of employee 

    str Name; 
    // Name of employee 
}; 

int main() 
{ 
    Employee e; 

    e.setID(5); 
    std::cout << e.getID() << std::endl; 
} 

一些人认为,如果你的getter/setter存取,你还不如让成员公开。其他人认为最好有getter/setter访问器,因为它允许你执行不变量/约束或更改各种实现细节。

至于访问私人会员:你不应该这样做。 It's technically possible, but don't do it.

0

假设Struct是一个错字。

通过删除结构体的名称,可以使中的Data结构变为匿名。 这将允许您直接使用Example[0].Identification_Number访问数据,但为了使其正常工作,您还必须公开该结构。

另一种选择是完全删除结构并直接存储数据作为Employee类的成员。

第三个选项是添加const访问器方法来返回结构中的数据。