用这个来表达正确性

时间:2013-09-30 23:55:40

标签: c++ const const-correctness

我有一个const方法,其中我想将类B的成员的属性设置为当前实例A(通过指针进行反向引用)

A类:

void A::foo () const
{
   ...
   ...
   B b;
   b.setA(this);
   ...
}

B组:

setA(A * Ap){
   this->pointerToA = Ap;
}

B * getA() {return pointerToA;}

A* pointerToA;

编译器不允许这样做......好的 现在我试着

B组:

setA(const A * Ap){
   this->pointerToA = Ap;
}

const A * getA() {return pointerToA;}

const A* pointerToA;

这解决了原来的问题,但现在我不能打电话给B:

...
this->getA()->anotherMethodOfA();
...

因为我得到“无法将'指针'从'const A'转换为'A&'

虽然我理解上面的问题,但我无法弄清楚,现在如何调用另一种方法,问题是什么......为什么会出现A& A在错误消息中,因为我无处引用A?

2 个答案:

答案 0 :(得分:1)

由于A是常量指针,因此您只能在其上调用const方法。有两种可能的解决方案:

  1. 如果你需要在A上调用非const方法:从const删除void A::foo () const说明符,因为该函数实际上通过调用B来修改this
  2. 如果您不需要在A上调用非const方法:make anotherMethodOfA以及在B const内的A上调用的任何其他方法。
  3. 您获得的错误是合法的,否则您将违反纯方法的定义。

    如果您需要fooconst,并且在foo内的A上调用的方法不会以通过公共接口可见的方式更改它(例如,执行一些缓存或您也可以尝试将mutable说明符与修改后的字段一起使用。但请不要滥用此功能!

答案 1 :(得分:0)

您可以使用Scott Meyers'解决方案解决此问题:所有getter的两个版本,一个non-const版本调用const版本和const版本返回预期变量:

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()); }
相关问题