您的位置:首页 > 其它

Relationship of the this pointer and (non-)const member function

2011-11-16 16:23 477 查看
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 *).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐