In C++ code, there is a class named Base
. The const Base *p1
pointer cannot call the set
method, but can call the get
method. However, the get
method must be declared as const
.
We can use it as a data receiver, and because of the existence of const, the receiver cannot change the data inside now.
Example:
#include <iostream>
using namespace std;
class Base {
private:
int value;
public:
Base(int val = 0) : value(val) {}
void setValue(int val) {
value = val;
}
int getValue() const {
return value;
}
int getValueNonConst() {
return value;
}
};
int main() {
Base obj(42);
// 创建const指针
const Base* p1 = &obj;
// 以下操作是允许的:
cout << "通过const指针调用const方法: " << p1->getValue() << endl;
// 以下操作会编译错误,因为const指针不能调用非const方法:
// p1->setValue(100); // 错误!const指针不能调用非const方法
// p1->getValueNonConst(); // 错误!const指针不能调用非const方法
// 普通指针的对比
Base* p2 = &obj;
p2->setValue(100); // 允许
cout << "通过普通指针修改后: " << p2->getValue() << endl;
return 0;
}
/*
通过const指针调用const方法: 42
通过普通指针修改后: 100
*/