从一个编译错误去理解this指针。
编译错误的示例
1 | class Car { |
- 编译后会出现以下错误:
1
main.cpp:15: error: C2662: “const int &Car::weight(void)”: 不能将“this”指针从“const Car”转换为“Car &”
为什么会这样?
- 编译器里面
const int &weight()与const int &weight(Car *this)是等价的; - 因为
Car类的weight函数虽然没有参数传入,但实际上编译器自动隐含的传入this指针; - 由于
const Car car被申明为常量实例,导致car实例所引用的weight函数的this指针也需要为const修饰;
怎么做?
- 将
const int &weight()改为const int &weight() const即可。
总结
const int &weight() const中,第一个const修饰weight返回值,第二个const修饰this指针;- 常量类只能访问使用
const修饰的函数。