2012年5月17日 星期四

[C++] error C2662 cannot convert 'this' pointer from 'const class' to 'class &


Look at following sample
class myClass
{
public:
    int get();
private:
    int m_member;
};

int myClass::get()
{
    return m_member;
}

int main()
{
    const myClass own;
    own.get();  // compiling error
    return 0;
}

A const object try to call non-const function, it is risk to change value of const object.
For the reason, we have to define myClass::get() to be a const function so that we could call the function by a const object.
int myClass::get() const

Or we also can define own to be a non-const object.
myClass own;


Reference: 
http://hi.baidu.com/idealsoft/blog/item/629ae129a7f14afb99250af4.html http://forums.codeguru.com/archive/index.php/t-416873.html

沒有留言:

張貼留言