有以下几个优势:
1. 语法一致性:访问class成员时每一个都是函数,不需要记住是否需要小括号
2. 使成员变量的处理有更精准的控制
class AccessLevels {
public:
int getReadOnly() const { return readOnly; }
void setReadWrite(int value) { readWrite = value; }
int getReadWrite() const { return readWrite; }
void setWriteOnly(int value) { writeOnly = value; }
private:
int noAccess; // 无访问动作
int readOnly;
int readWrite;
int writeOnly;
};
3. 实现良好的封装特性
class SpeedDataCollection {
public:
void addValue(int speed) {
speedList.push_back(speed);
}
double averageSoFar() const {
int sum = std::accumulate(speedList.begin(), speedList.end(), 0);
return static_cast<double>(sum)/speedList.size();
}
private:
std::vector<int> speedList;
};