目录
在 C++ 中,const
修饰成员函数或对象时,本质上是修饰 this
指针,使其指向 const
对象,进而保证成员函数不能修改成员变量(除 mutable
变量外)。在这个过程中this指针的变化情况:从常量指针变为指向常量的常量指针。
预备知识了解【this指针是一个常量指针】
#include<iostream>
class Person{
public:
int m_A; // 成员变量
// this 指针指向当前调用该成员函数的对象【this指针的本质:this指针是一个常量指针,指针的指向不能修改,指针指向的内容可以修改】
void showPerson() {
this->m_A = 100;
std::cout<<"this指针指向的地址:"<<this<<std::endl;
}
};
int main(){
Person p1;
p1.showPerson();
std::cout<<"p1 对象的地址:"<<&p1<<std::endl;
return 0;
}
//输出:
// this指针指向的地址:0x61fe4c
// p1 对象的地址:0x61fe4c
this 指针的本质:Person* const this;常量指针【指针的指向不能修改,指针指向的内容可以修改。
如果我现在让this指向的内容也不可以被修改,我对上面的常量指针做一点小修改,修改为: const Person* const this; 指向常量的常量指针。
根据上面的理解,就可以将代码中成员函数部分修改为下面的形式。成员函数名称后面加了一个const,这个const其实就是const Person* const this; 的第一个const,如下所示:
void showPerson() const{
std::cout<<"成员变量 m_A 的值:"<<m_A<<std::endl;
}
修改后的整体代码如下:
#include<iostream>
class Person{
public:
int m_A=10; // 成员变量
void showPerson() const{
std::cout<<"成员变量 m_A 的值:"<<m_A<<std::endl;
// m_A=100; // ❌ 企图修改 this 指针指向的内容
// this->m_A=100; // ❌ 与上一行代码本质一致
}
};
int main(){
Person p1;
p1.showPerson();
return 0;
}
// 输出:
// 成员变量 m_A 的值:10
C++ 中的 const
关键字
1. 常成员函数(const
成员函数)
- 在成员函数后加
const
,该函数称为常函数(const
成员函数)。 - 常函数内不能修改成员变量(
mutable
修饰的变量除外)。 - 作用:保证成员函数不会修改对象状态,提高代码安全性。
✅ 示例
class Example {
private:
int value;
mutable int cache; // `mutable` 变量可以在 `const` 函数中修改
public:
Example(int v) : value(v), cache(0) {}
void setValue(int v) { value = v; } // 普通成员函数,可修改成员变量
int getValue() const { return value; } // ✅ `const` 成员函数,不修改成员变量
void updateCache() const { cache = value * 2; } // ✅ `mutable` 变量可修改
};
2. 常对象(const
对象)
- 在对象前加
const
,则该对象为常对象,不能修改成员变量。 - 常对象只能调用
const
成员函数(即不会修改对象状态的函数)。
✅ 示例
int main() {
const Example obj(10); // `obj` 是常对象
std::cout << obj.getValue() << std::endl; // ✅ 允许调用 `const` 成员函数
obj.updateCache(); // ✅ `mutable` 变量可修改
// obj.setValue(20); // ❌ 错误:不能调用非 `const` 成员函数
return 0;
}
const Example obj;
的 本质:
obj 被修饰为 const
,那么 obj 内部的 this
也变成了 const Example*
,
这样 obj 只能调用 const
成员函数,否则编译会报错。
总结
概念 | 定义 | 规则 |
---|---|---|
常成员函数 | 在成员函数后加 const | 不能修改成员变量(mutable 变量除外) |
常对象 | 在对象前加 const | 只能调用 const 成员函数 |
✔ const
修饰成员函数时,本质上是修饰 this
指针,使 this
从 类名* const this;
变为 const 类名* const this;
,禁止修改成员变量(除 mutable
变量外)。
✔ const
修饰对象时,本质上是让对象内的 this
指针从 类名* const this;
变为 const 类名* const this;
,从而只能调用 const
成员函数。
✔ mutable
变量可以绕过 const
约束,在 const
成员函数中仍然可以修改。