从一个编译错误去理解this指针。
class Car {
public:
const int &weight()
{
return m_weight;
}
private:
int m_weight;
};
int main(int argc, char *argv[])
{
const Car car;
int weight = car.weight();
return 0;
}main.cpp:15: error: C2662: “const int &Car::weight(void)”: 不能将“this”指针从“const Car”转换为“Car &”constint&weight()与 constint&weight(Car*this)是等价的;Car类的 weight函数虽然没有参数传入,但实际上编译器自动隐含的传入 this指针;constCarcar被申明为常量实例,导致 car实例所引用的 weight函数的 this指针也需要为 const修饰;constint&weight()改为 constint&weight()const即可。constint&weight()const中,第一个 const修饰 weight返回值,第二个 const修饰 this指针;const修饰的函数。