c++ - 非常量成员引用在 const 对象上是可变的吗?

标签 c++ class struct reference member

鉴于以下情况:

struct S
{
    int x;
    int& y;
};

int main()
{
    int i = 6;
    const S s{5, i}; // (1)
    // s.x = 10;     // (2)
    s.y = 99;        // (3)
}

为什么当sconst时允许(3)

(2) 会产生编译器错误,这是预期的。我预计 (3) 也会导致编译器错误。

最佳答案

Why is s.y = 99 allowed when s is const?

const S ss.y 类型不是 int const& 而是 int&。它不是对 const int 的引用,而是对 int 的 const 引用。当然,所有引用都是恒定的,您不能重新绑定(bind)引用。

如果您想要一个类型 S',而该类型的 const 对象不能用于更改 y 引用的值,该怎么办?您不能简单地做到这一点,必须求助于访问器或任何非常量函数(例如 operator=):

class U
{
    int& _y;
public:
    int x;
    void setY(int y) { _y = y; } // cannot be called on const U
};

关于c++ - 非常量成员引用在 const 对象上是可变的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74681127/

相关文章:

c++ - 针对 64 位错误编译 GINA.dll

javascript - 关于在 React 中使用 ES6 类

c++ - 如何在可变大小的类中创建指针数组?

python - 将 Python 中的二进制文件读入结构

c - 结构和段错误

C++ 包装 C struct *and* and functions

c++ - 在递归 lambda 中按值捕获

c++ - 为什么我得到 "end of file found before the left brace ' {' in hashtable.h(8)"?

css - 在 Sencha ExtJS 框架中应该删除什么 CSS 类的组件事件? (烦人的红线)

c++ - 用 C++ 读取文本文件最优雅的方法是什么?