常函数
- 成员函数后加const,称为常函数。
- 常函数内部不可以修改成员变量。
- 常函数内可以改变加了mutable修饰的成员变量。
code:#include <iostream>using namespace std;class Horse{public:int age = 3;mutable string color = "white";void show_age() const {color = "black"; cout << "it is " << age << endl;}};int main(){Horse horse1;horse1.show_age();system("pause");return 0;}
result:it is 3
常对象
- 在声明对象前在const,常对象,常对象的内容不可以修改。
- 常对象只能调用常函数。
- 常对象可以修改mutable修饰的成员变量。
code:#include <iostream>using namespace std;class Horse{public:int age = 3;mutable string color = "white";void show_info() const {color = "black"; cout << "it is " << age << endl;}void show_info_1(){color = "black";cout << "it is " << age << endl;}};int main(){Horse horse1;horse1.show_info();const Horse horse2; horse2.color = "brown"; cout << horse2.age << endl;cout << horse2.color << endl;horse2.show_info();system("pause");return 0;}
result:it is 33brownit is 3