常量对象只能调用const成员函数,因为const对象的this指针为const类型,无法调用隐含非const this指针的普通成员函数;const成员函数承诺不修改对象非mutable成员,确保对象状态安全,提升多线程安全性;mutable成员可被const函数修改,适用于缓存或计数器场景。

在C++中,const成员函数和常量对象是紧密相关的两个概念,它们共同确保对象状态在不该被修改的情况下不被意外修改。
常量对象只能调用const成员函数
当一个对象被声明为const时,意味着它的数据成员在整个生命周期中都不能被修改。因此,只能调用那些被标记为const的成员函数。
例如:
class MyClass {
public:
int getValue() const { return value; } // const成员函数
void setValue(int v) { value = v; } // 非const成员函数
private:
int value = 0;
};
const MyClass obj;
obj.getValue(); // ✅ 允许:const函数
// obj.setValue(5); // ❌ 错误:不能在const对象上调用非const函数
这是因为非const成员函数隐含地接收一个指向非const对象的this指针,而const对象只能传递const this指针。
const成员函数的定义与作用
在成员函数声明或定义的参数列表后加上const关键字,表示该函数不会修改类的数据成员(除非成员被声明为mutable)。
立即学习“C++免费学习笔记(深入)”;
const成员函数的this指针类型是
const ClassName*,因此不能修改对象的任何非mutable成员。
- 提高代码安全性:防止意外修改对象状态
- 支持对const对象的操作
- 使函数接口语义更清晰
- 在多线程环境中更安全(可被多个线程同时调用)
mutable关键字的特殊用途
有时我们需要在const成员函数中修改某个特定成员,比如用于缓存或计数器。这时可以将该成员声明为mutable。
class Logger {
public:
void log(const std::string& msg) const {
count++; // ✅ 允许:count是mutable
std::cout << msg << std::endl;
}
int getCount() const { return count; }
private:
mutable int count = 0; // 即使在const函数中也可修改
};
mutable成员突破了const的限制,但应谨慎使用,仅用于不影响对象逻辑状态的场景。
const重载:提供不同版本的成员函数
C++允许对成员函数进行const重载,编译器会根据对象是否为const自动选择合适的版本。
class Container {
public:
int& at(size_t index) { return data[index]; }
const int& at(size_t index) const { return data[index]; }
private:
int data[100];
};
Container c1;
const Container c2;
c1.at(0) = 10; // 调用非const版本,允许赋值
// c2.at(0) = 10; // 错误:c2是const,返回const引用,不能赋值
int x = c2.at(0); // ✅ 正确:读取值
这种技术在标准库中广泛使用,如
std::vector::operator[]。
基本上就这些。合理使用const成员函数和常量对象,能显著提升代码的健壮性和可维护性。不复杂但容易忽略。










