应用于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()。
是否有某种方法可以将对象的constness传播给返回其成员引用的方法?
您需要提供getC()
的非const重载。例如
C& getC() { return c; };
相关文章:
- 从函数返回const char*数组
- 在 const 函数中通过引用和指针返回之间的区别
- 为什么返回类型的'const'限定符对标有 __forceinline/内联的函数没有影响?
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 如果我在 const 函数上使用指针,我可以返回什么?
- 将返回类型专用化为 void 或 const 左值引用
- 为什么 const 函数返回左值而不是右值?
- 为什么"std::set::erase(const key_type&)"返回"size_type"而不是"bool"?
- 用 decltype 和 auto 推导出 const(返回)类型
- 延长函数的寿命延长 由 const& 获取参数并由 const& 返回
- 如何将指向指针列表的私有指针作为 const 返回
- 我应该在简单的访问成员函数中使用 const 返回类型吗?
- 如何可能移动const返回的对象
- 在具有专用器的模板类上正确使用 const 返回值
- 为什么 std::max 通过 const 返回?
- 德尔福中C++“const”返回类型相当于什么
- g++编译器忽略const返回类型
- 我应该什么时候通过 T const& 返回?
- c++编译器可以对const返回值执行RVO吗?