🚚
在 C++ 中,将成员函数修饰为 const 有一个含义:该函数不能修改对象的非静态数据成员。当一个成员函数被声明为 const 时,它承诺不会对对象进行任何修改操作。
具体来说,以下内容受到 const 成员函数的限制:
- 非静态数据成员:在 const 成员函数中,不能直接或间接地修改对象的任何非静态数据成员。这包括通过赋值、调用非 const 成员方法等方式。
- 调用其他非 const 成员方法:由于 const 成员函数保证不修改对象状态,因此它们只能调用其他被声明为 const 的成员方法。无法调用没有被声明为 const 的非 const 方法。
- 修改指针类型的内容:如果一个指针是类中的 non-const 数据成员,并且该指针指向某个内存区域,则在 const 成员函数中不能通过该指针来更改其所指向内存位置上的值。
需要注意的是,在使用常量引用作为参数传递给普通(non-const)成员方法时,默认情况下编译器会自动选择匹配最佳候选项(即根据是否存在合适版本)。但如果使用常量引用作为参数传递给了常量(const)成员方法,则只能调用该类中被声明为 const 的成员方法。
当将一个成员函数修饰为 const,以下是一些具体的例子说明哪些值不能被改变:
非静态数据成员的修改:
class MyClass {
public:
int value;
void nonConstMethod() {
value = 10; // 可以修改非 const 成员函数中的非静态数据成员
}
void constMethod() const {
// value = 20; // 错误!不能在 const 成员函数中修改非静态数据成员
int newValue = 20;
// this->value = newValue; // 错误!也无法通过 this 指针来修改值
}
};
调用其他非 const 成员方法:
class MyClass {
public:
void nonConstMethod() {}
void constMethod() const {
// nonConstMethod(); // 错误!无法调用其他非常量(non-const)成员方法
anotherConstMethod(); // 正确!可以调用已经声明为常量(const)的其他成员方法
}
void anotherConstMethod() const {}
};
修改指针类型内容:
class MyClass {
public:
int* ptr;
MyClass(int val) : ptr(new int(val)) {}
~MyClass() { delete ptr; }
void modifyValue(int newVal) {
*ptr = newVal;
}
void printValue() const {
std::cout << "Value: " << *ptr << std::endl;
//*ptr = 100; //!错误, 在const成语函敿内不允许修改指针所指向的内存位置上的值
}
};
在 printValue() 这个 const 成员函数中,我们可以读取 ptr 指针所指向的值,但是不能修改它。