常成员函数
1、基本介绍
-
函数后面跟个 const,是 C++ 的常成员函数语法
-
常成员函数不会修改任何成员变量(mutable 成员除外)
-
常成员函数不可以调用其他成员函数,可以调用其他常成员函数
-
const 对象只能调用 const 函数
-
可以提供重载,普通对象优先调用非 const 版本
2、演示
- 基本使用
cpp
class Student {
private:
int age;
mutable int cache;
public:
int getAge() const {
// age = 1; // 不能修改
// cache = 1; // 可以修改
// setAge(10); // 不能调用
// setCache(10); // 可以调用
return age;
}
void setAge(int a) {
age = a;
}
void setCache(int c) const {
cache = c;
}
};
- const 对象只能调用 const 函数
cpp
class Student {
private:
int age = 10;
mutable int cache;
public:
int getAge() const {
return age;
}
void setAge(int a) {
age = a;
}
void setCache(int c) const {
cache = c;
}
};
cpp
const Student s = Student();
cout << s.getAge() << endl; // 可以调用
s.setAge(10); // 不能调用
s.setCache(10); // 可以调用
- 可以提供重载,普通对象优先调用非 const 版本
cpp
class Student {
private:
int age = 10;
mutable int cache;
public:
int getAge() {
age = 20;
return age;
}
int getAge() const {
return age;
}
void setAge(int a) {
age = a;
}
void setCache(int c) const {
cache = c;
}
};
cpp
Student s = Student();
cout << s.getAge() << endl;
# 输出结果
20