常函数

  • 成员函数后加 const 后,我们称这个函数为常函数

  • 常函数内不可修改成员属性

  • 成员属性声明时加关键字 mutable 后,在常函数中依然可以修改

代码示例

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
#include<iostream>
using namespace std;

class Person {
public:
void showPerson() const{
//在成员函数后面加const,修饰的是 this指向 ,让指针指向的值也不可修改
//this指针的本质是 指针常量 ,指针的指向是不可修改的
this->m_A = 100;//报错,常函数内不可修改成员属性
//const Person * const this
this = NULL;//报错,不可修改 this指针 的指向
//Person * const this

this->m_B = 100;// 正常

}

int m_A;
mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值
};

int main() {
Person p;
p.showPerson();
return 0;
}

常对象

  • 声明对象前加 const 称为该对象为常对象

  • 常对象只能调用常函数

代码示例

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
#include<iostream>
using namespace std;

class Person {
public:
void showPerson() const{
//在成员函数后面加const,修饰的是 this指向 ,让指针指向的值也不可修改
//this指针的本质是 指针常量 ,指针的指向是不可修改的
this->m_A = 100;//报错,常函数内不可修改成员属性
//const Person * const this
this = NULL;//报错,不可修改 this指针 的指向
//Person * const this

this->m_B = 100;// 正常

}

void func() {
m_A = 100;
}

int m_A;
mutable int m_B;//特殊变量,即使在常函数中,也可以修改这个值
};

int main() {
const Person p;//在对象前加 const ,变为常对象
p.m_A = 100;//报错, 常对象不允许修改普通的成员变量
p.m_B = 100;//正常,m_B是特殊值,在常对象下也可以修改


p.showPerson();//正常
p.func();//报错,常对象只能调用常函数,因为扑通成员函数可以修改属性

return 0;
}