Let's see the example first.
class A {
public:
A() { a = 0; }
int& Get() { return a; }
void Test() const { this->Get(); }
void Test() { this->Get(); }
private:
int a;
};
int main() {
A obj;
obj.Test();
return 0;
}
Obviously, it is wrong due to the const member function and int& return value. However, how to modify it? The accurate version should be like this:
class A {
public:
A() { a = 0; }
int& Get() { return a; }
void Test() const { ((A *)this)->Get(); }
void Test() { this->Get(); }
private:
int a;
};
int main() {
A obj;
obj.Test();
return 0;
}Through this modification, we can conclude that the type of this pointer is quite different. As we can see, in the const version, the object pointed by this pointer cannot be modified (type: const A *), while in the common version, it can be modified (type: A *).
本文详细解析了在C++中通过修改this指针类型来避免常量成员函数返回引用时可能引发的错误修改常量对象的问题,并提供了解决方案。
2931

被折叠的 条评论
为什么被折叠?



