考虑以下代码:
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 中,我不保证常量,我确实想更改完全相同的 b.getC()。
是否有某种方法可以将对象的常量性传播到返回对其成员的引用的方法?
最佳答案
您需要提供 getC()
的非常量重载。例如
C& getC() { return c; };
关于c++ - 应用于 const 和非常量对象的引用返回方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813598/