문제

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:

  1. if you need to call a non-const method on A: remove the const specifier from void A::foo () const, since the function is actually modifying this through the calls to B.
  2. if you don't need to call a non-const method on A: make 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 (e.g. 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()); }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top