常函数
- 成员函数后加const,称为常函数。
- 常函数内部不可以修改成员变量。
- 常函数内可以改变加了mutable修饰的成员变量。
code:
#include
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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
常对象
- 在声明对象前加const,常对象,常对象的内容不可以修改。
- 常对象只能调用常函数。
- 常对象可以修改mutable修饰的成员变量。
code:
#include
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 3
3
brown
it is 3
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42