08.常函数和常对象
1.常函数
可以在成员函数的参数列表后加一个const,表示这个函数是常函数
- 常函数中,不允许修改属性值
- 常函数中,不允许调用普通函数,只能调用其他常函数
c++
class Person {
public:
int age;
void constFn(int age) const {
// this->age = age; // 错误,表达式必须是可修改的左值
// display() // 错误
}
void display() {
cout << "这是一个普通函数" << endl;
}
};2.常对象
定义对象时,使用const修饰符,即为常对象
- 常对象可以读取任意属性的值,但不允许修改
- 常对象只能调用常函数,不能调用普通函数
c++
#include<iostream>
using namespace std;
class Person {
public:
int age=18;
void constFn() const {
cout << "这是一个常函数" << endl;
}
void display() {
cout << "这是一个普通函数" << endl;
}
};
int main() {
const Person p1;
// p1.age = 100; // 错误,常对象不可修改变量
cout << p1.age << endl; // 18
// p1.display(); // 错误,常对象调用普通对象
p1.constFn(); // 这是一个普通函数
return 0;
}3.mutable
mutable用来修饰成员变量,使变量可以在常函数中修改,也可以由常对象修改
c++
#include<iostream>
using namespace std;
class Person {
public:
mutable int age = 18;
void constFn() const {
// 常函数中更改
age = 24;
}
};
int main() {
const Person p1;
cout << p1.age << endl; // 18
p1.constFn();
cout << p1.age << endl; // 24
p1.age = 25; // 常对象中修改
cout << p1.age << endl; // 25
return 0;
}