简体   繁体   English

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

[英]Reference returning method applied on const and non-const object

Consider the following code: 请考虑以下代码:

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();
}

Since my_method guarantees const, b.getC() must also be const. 由于my_method保证const,b.getC()也必须是const。 In f however, I do not guarantee constness and I do want to change the very same b.getC(). 然而,在f中,我不保证constness,我确实想要改变相同的b.getC()。

Is there some sort of a way to propagate the constness of an object to methods returning references to its members? 是否有某种方法可以将对象的常量传播给返回对其成员的引用的方法?

You need to provide a non-const overload of getC() . 您需要提供getC()的非常量重载。 For example 例如

C& getC() { return c; };

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

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