从一个编译错误去理解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
修饰的函数。