开发者

Cannot convert 'this' pointer to Class&

Can someone tell why i'm getting this error when compling this class?

class C
{
public:
    void func(const C &obj)
    {
       //body
    }

private:
    int x;
};开发者_如何学Go

void func2(const C &obj)
{
    obj.func(obj);
}

int main() { /*no code here yet*/}


The C::func() method doesn't promise that it won't modify the object, it only promises that it won't modify its argument. Fix:

   void func(const C &obj) const
    {
       // don't change any this members or the compiler complains
    }

Or make it a static function. Which sure sounds like it should be when it takes a C object as an argument.


You need to mark C::func(const C &obj) as const as you're calling it from a const object. The correct signature would look like this:

void func(const C& obj) const


The problem is that in func2() you're calling a non-const function (C::func()) using a const object.

Change the signature of C::func() to:

void func(const C &obj) const
{
    // whatever...
}

so that it can be called with const objects.


Because:

this

is a const pointer to current obj.

Therefore you can either make the func to be const:

class C
{
public:
    void func(const C &obj) const
    {
       //body
    }

private:
    int x;
};

void func2(const C &obj)
{
    obj.func(obj);
}

int main() { 
return 0;
}

OR

you can remove the constness of the this pointer like this:

class C
{
public:
    void func(const C &obj)
    {
       //body
    }

private:
    int x;
};

void func2(const C &obj)
{
    (const_cast<C &>(obj)).func(obj);
}

int main() { 
return 0;
}

Hope that helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜