我是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 :(得分:3)
使用这样的setter和getter:
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");
答案 1 :(得分:0)
basic_string
类已经实现了一个“设置器”:
employee1.name.assign("Mary");
employee2.gender.assign("Female");
如果您想要像在问题中写的那样访问name
和gender
,则需要同时指出public
,因为正确指出了@sop。