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

Kor*_*ory 2 c++ struct reference class 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)
}
Run Code Online (Sandbox Code Playgroud)

为什么什么时候(3)允许?sconst

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

YSC*_*YSC 5

为什么什么时候s.y = 99允许?sconst

s.yfor的类型const S s不是int const&but int&。它不是对 const int 的引用,而是对 int 的 const 引用。当然,所有引用都是常量,您不能重新绑定引用。

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

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