应用于const和非const对象的引用返回方法

时间:2014-07-17 21:10:58

标签: c++ const

请考虑以下代码:

class A{

  my_method(const B& b){
    import_something_from_c(this, b.getC()); // does some sort of copying
  }

}

class B{
  const C& getC() const { return c; };
}

function f(B b){
  b.getC().changeSomething();
}

由于my_method保证const,b.getC()也必须是const。然而,在f中,我不保证constness,我确实想要改变相同的b.getC()。

是否有某种方法可以将对象的常量传播给返回对其成员的引用的方法?

1 个答案:

答案 0 :(得分:3)

您需要提供getC()的非常量重载。例如

C& getC() { return c; };
相关问题