I have a const method in which I want to set an attribute of a member of class B to the current instance A (to make a backreference by pointer)
Class A:
void A::foo () const
{
...
...
B b;
b.setA(this);
...
}
Class B:
setA(A * Ap){
this->pointerToA = Ap;
}
B * getA() {return pointerToA;}
A* pointerToA;
The compiler doesnt allow this... Ok Now I tried to
Class B:
setA(const A * Ap){
this->pointerToA = Ap;
}
const A * getA() {return pointerToA;}
const A* pointerToA;
This solves the original problem, but now I cannot call in B:
...
this->getA()->anotherMethodOfA();
...
because I get "cannot convert 'this' pointer from 'const A' to 'A&'
Although I understand the upper problem, I cannot figure out, how to call the other method now and what's the problem...Why is there a A& in the error message, since I have nowhere a reference to A?
Since A is a constant pointer, you can only call const
methods on it. There are two possible solutions:
const
specifier from void A::foo () const
, since the function is actually modifying this
through the calls to B. anotherMethodOfA
and any other method invoked on A inside B const
too. The error you get is legitimate, otherwise you would be violating the definition of pure method.
If you need foo
to be const
and the methods invoked on A inside foo
do not change it in a way that is visible through the public interface (eg perform some caching or the like), you could also try using the mutable
specifier with modified fields. But don't abuse this feature, please!
You can solve the issue by using Scott Meyers'
solution: Two versions of all getters, one non-const
version that calls the const
version and the const
version returns the intended variable:
const A* GetA() const { return pointerToA; }
//Cast 'this' to a const reference to B
//(this allows you to call the const version of the getter instead of infinite recursion).
//Cast away the const-ness of the result returned by the const version
//and return the non-const version.
A* GetA() { return const_cast<A*>(static_cast<const B&>(*this).getA()); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.