对于含有许多数据成员的类, 通常需要提供数据的set和get接口,下面的代码提供了一种set和get的形式,接口比较简洁:
#include <memory>
#include <iostream>
#include <vector>
using namespace std;
class Person
{
public:
Person(const string& name, int age) :
mName(name), mAge(age) {
}
const string& name() const {
return mName;
}
string& name() {
return mName;
}
void name(string& name) {
mName = name;
}
int age() const {
return mAge;
}
int age() {
return mAge;
}
void age(int age) {
mAge = age;
}
private:
string mName;
int mAge;
};
int main() {
cout << "at first:"<< endl;
Person p1("zhangsan", 26);
Person p2("lisi", 19);
cout << p1.name() << " " << p1.age() << endl;
cout << p2.name() << " " << p2.age() << endl;
cout << "3 years passed:"<< endl;
p1.age(p1.age()+3);
p2.age(p2.age()+3);
cout << p1.name() << " " << p1.age() << endl;
cout << p2.name() << " " << p2.age() << endl;
return 0;
}