1. 原因解析
在 C++ 中,如果一个对象是 const
,那么它的成员变量不能被修改。因此,为了保证这一特性,编译器只允许 const
对象调用常量成员函数(即 const
修饰的成员函数),从而防止 const
对象被修改。
常量成员函数是指声明时带有 const
关键字的成员函数,例如:
class MyClass {
public:
void regularFunction() { // 非常量成员函数
data = 10; // 修改数据
}
void constFunction() const { // 常量成员函数
// data = 10; // ❌ 错误!不能修改数据
}
private:
int data;
};
如果 const
对象允许调用非 const
成员函数,可能会修改 const
对象的内部数据,违背 const
语义,因此编译器会报错。
2. 代码示例
(1)常量对象只能调用常量成员函数
#include <iostream>
using namespace std;
class MyClass {
public:
void regularFunction() {
cout << "非const成员函数" << endl;
}
void constFunction() const {
cout << "const成员函数" << endl;
}
};
int main() {
const MyClass obj; // 定义常量对象
// obj.regularFunction(); // ❌ 编译错误,常量对象不能调用普通成员函数
obj.constFunction(); // ✅ 允许,常量对象可以调用 const 成员函数
return 0;
}
输出:
const成员函数
(2)常量对象的引用也只能调用 const
成员函数
void printClass(const MyClass& obj) {
// obj.regularFunction(); // ❌ 编译错误
obj.constFunction(); // ✅ 允许
}
当 obj
是 const MyClass&
类型的引用时,它只能调用 const
成员函数,防止修改原始对象。
3. 结论
- 常量对象(
const MyClass obj
)只能调用const
成员函数。 - 常量对象的引用(
const MyClass& obj
)也只能调用const
成员函数。 const
成员函数不能修改成员变量,除非该变量用mutable
关键字修饰。