簡體   English   中英

應用於const和非const對象的引用返回方法

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

請考慮以下代碼:

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

是否有某種方法可以將對象的常量傳播給返回對其成員的引用的方法?

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

C& getC() { return c; };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM