鉴于以下情况:
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)
}
为什么当s
是const
时允许(3)
?
(2)
会产生编译器错误,这是预期的。我预计 (3)
也会导致编译器错误。
最佳答案
Why is
s.y = 99
allowed whens
isconst
?
const S s
的 s.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/