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

Reference returning method applied on const and non-const object

本文关键字:const 返回 方法 引用 对象 和非 应用于      更新时间:2023-10-16

考虑以下代码:

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()。

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

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

C& getC() { return c; };