2012-12-03 5 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; 

그렇지 않으면 무엇이 적합한 컨테이너입니까? 이 데이터 집합을 처리 할 때 목록의 목록이 더 좋을까요? 당신이했습니다으로 Data 구조가이 경우에 완전히 불필요한 것을

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 
}; 

참고 :

+1

공개적으로 사용할 수있게하려면'구조체 '를 비공개로 만들어야하는 이유는 무엇입니까? 아니면'Struct Data {'a typo? – Cornstalks

+2

그리고 왜 '데이터'구조가 첫 번째 위치에 있습니까? 'Data' 멤버들을 모두'Employee' 클래스에 직접 두는 것은 어떻습니까? –

+0

여기의 컨테이너는 완전히 관련이 없으므로 개인 회원에게 모두 액세스하는 방법에 대해 혼란스러워하는 것 같습니다. 그 대답은 물론 당신이 가정하지 않은 것입니다; 그게 전부입니다. – GManNickG

답변

1

그것은 당신이있는 그대로,하지만 몇 가지 수정을 당신이 일을 할 수 제공하는 코드 불가능 제시했다. 방금 클래스 내의 모든 데이터 멤버를 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 접근자를 갖는 것이 더 좋다고 주장하는데, 불변 식/제약 조건을 적용하거나 다양한 구현 세부 사항을 변경할 수 있기 때문입니다.

비공개 멤버를 액세스하는 방법 : 당신은하지 않아야합니다. It's technically possible, but don't do it.

0

가정하면 Struct은 오타입니다.

Data 구조체는 Employee 구조체를 구조체 이름을 제거하여 익명으로 만들 수 있습니다. 이렇게하면 Example[0].Identification_Number으로 직접 데이터에 액세스 할 수 있지만 올바르게 작동하려면 구조체를 공개해야합니다.

또 다른 옵션은 구조체를 완전히 제거하고 데이터를 Employee 클래스의 멤버로 직접 저장하는 것입니다.

세 번째 옵션은 const 접근 자 메소드를 추가하여 구조체의 데이터를 반환하는 것입니다.

관련 문제