繁体   English   中英

const正确性与此

[英]const correctness with this

我有一个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();
...

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

尽管我理解了上面的问题,但是我不知道现在该如何调用另一个方法,这又是什么问题...为什么错误消息中出现A&,因为我无处引用A?

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

  1. 如果你需要调用非const方法上的一个:去掉const从符void A::foo () const ,因为该功能实际上是修改this通过调用B.
  2. 如果您不需要在A上调用非const方法:请在B const内部也使anotherMethodOfA和在A上调用的任何其他方法成为可能。

您得到的错误是合法的,否则您将违反纯方法的定义。

如果您需要foo作为const并且在foo内部A上调用的方法没有以通过公共接口可见的方式更改它(例如,执行某些缓存等操作),则也可以尝试使用具有mutable字段的mutable说明符。 但是请不要滥用此功能!

您可以使用Scott Meyers'解决方案来解决该问题:所有吸气剂的两个版本,一个调用const版本的non-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()); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM