Cannot convert this pointer
I have a class Foo
which looks like this
class Foo
{
public:
void set_bar(int val)
{
_bar = val;
}
protected:
int _bar;
};
which is inherited by class Baz
which is declared as follows:
class Baz
: public Foo
{
public:
void set_baz(int val)
{
_baz = val;
}
protected:
int _baz;
};
and then i have a Factory
class which contains a member variable of type Baz
.
class Factory
{
protected:
Baz _baz;
public:
const Baz& get_baz() const
开发者_如何学Go{
return _baz;
}
};
If I used Factory
like this:
Factory f;
f.get_baz().set_bar(1);
It throws this error C2662: 'Foo::set_bar' : cannot convert 'this' pointer from 'const Baz' to 'Foo &'
You need to provide a non-const version of Factory::get_baz that returns a non-const reference to Baz:
class Factory
{
protected:
Baz _baz;
public:
const Baz& get_baz() const
{
return _baz;
}
Baz& get_baz()
{
return _baz;
}
};
When using a const Factory, the const version of get_baz will get invoked, otherwise the non-const version of get_baz will get invoked.
You should also refrain from using leading underscores in your names. See What are the rules about using an underscore in a C++ identifier?.
The object returned by get_baz
is constant, you cannot modify its contents.
After calling get_baz you are getting constant object and constant object can call only constant function.
You can only change the value if you return a non-const reference to your object.
If you return a non-const reference, why not just make the member public? You'll get the same effect...
精彩评论