【问题标题】:const correctness with thisconst 正确性
【发布时间】:2013-09-30 23:55:40
【问题描述】:

我有一个 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的引用?

【问题讨论】:

    标签: c++ constants const-correctness


    【解决方案1】:

    由于 A 是一个常量指针,你只能在它上面调用const 方法。有两种可能的解决方案:

    1. 如果您需要在 A 上调用非常量方法:从 void A::foo () const 中删除 const 说明符,因为该函数实际上是通过对 B 的调用来修改 this
    2. 如果您不需要在 A 上调用非常量方法:也可以在 B const 内的 A 上调用 anotherMethodOfA 和任何其他方法。

    你得到的错误是合法的,否则你就违反了纯方法的定义。

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

    【讨论】:

    • ;-) 2. 帮助。当然 anotherMethodOfA 必须是 const,否则可以修改对象。谢谢你的提示 - 我为此奋斗了几个小时,现在它变得 100% 清晰......
    【解决方案2】:

    您可以使用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()); }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多