2014-12-02 4 views
0

저는 C++을 처음 사용하기 때문에 답변을 찾을 수 없습니다. 다음 코드를 작성하고 싶습니다.같은 멤버 함수로 다른 멤버를 어떻게 변경합니까?

#include <iostream> 
using namespace std; 

class Employee{ 
private: 
    string name; 
    string gender; 
public: 
    void display(); 
    void update(string); 
    Employee(string a, string b){ 
      name = a; 
      gender = b; 
    }; 
    ~Employee(){}; 
}; 

void Employee::display(void){ 
    cout << "Name: " << name << endl; 
    cout << "Gender: " << gender << endl; 
    } 

void Employee::update(string a){ 
/* 
    a function that updates either the 
    name element or gender element 
    based on which element it is used by. 
*/ 
    } 

int main(){ 
    Employee employee1 ("Joe","Male"); 
    Employee employee2 ("Jon","Male"); 


    employee1.display(); 
    employee2.display(); 

    employee1.name.update("Mary");   // This is what I want to do: Same function 
    employee2.gender.update("Female");  // for different elements of same type   

    employee1.display(); 
    employee2.display(); 

    return 0; 
} 

어떻게해야합니까? 함수 오버로드에 대해 생각했지만 두 요소가 같은 형식입니다. 여분의 값을 전달하고 코드가 엉성하게 보이게하고 싶지 않습니다. 어떤 아이디어? 고맙습니다. 이 같은

+0

"동일한 멤버 함수로 다른 요소를 어떻게 변경합니까?" - * 무엇? * ... 편집 : 아 글쎄, 지금 내가 가진 모든 것을 읽은 후에. 그러나 그 질문은 ... 잘 표현되지 않았습니다. – dom0

+1

제 의견으로는 회원은 비공개이므로 수업 외에서는 회원이 이용할 수 없습니다. 그래서 당신은 당신의 메인에'employee.name'을 사용할 수 없습니다 ... – sop

답변

3

사용 세터와 게터 하나는 기대하는 것처럼

void Employee::setName(const string &a) { 
    this->_name = a; // validate or whatever you need to do 
} 

const string &Employee::name() const { 
    return this->_name; 
} 

void Employee::setGender(const string &a) { 
    // .... 
} 

사용이

employee1.setName("Mary"); 
employee2.setGender("Female"); 
+0

고정, 고마워요. – dom0

+0

getter에서 콜론':'을 잊어 버렸습니다. – sop

+0

질문에 답할 수 없습니다. '같은 멤버 함수로 다른 요소를 변경하려고합니다.' – alain

0

basic_string 클래스는 이미 '세터'을 구현합니다

employee1.name.assign("Mary"); 
employee2.gender.assign("Female"); 

당신이 원하는 경우 귀하의 퀘스트에 기록한 것처럼 namegender에 액세스하십시오. @ soop을 올바르게 지적 했으므로 두 가지 모두를 만들어야합니다.

+1

회원은 비공개이므로 'employee1.name.assign ("X");' – sop

+0

참 고맙습니다. 나는 나의 대답을 업데이트했다. – alain

관련 문제