gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:25:49 25 4
gpt4 key购买 nike

鉴于以下情况:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com