【发布时间】:2021-01-08 16:13:56
【问题描述】:
我正在研究我的代码的 const 正确性,只是想知道为什么这段代码可以编译:
class X
{
int x;
int& y;
public:
X(int& _y):y(_y)
{
}
void f(int& newY) const
{
//x = 3; would not work, that's fine
y = newY; //does compile. Why?
}
};
int main(int argc, char **argv)
{
int i1=0, i2=0;
X myX(i1);
myX.f(i2);
...
}
据我了解,f() 正在更改对象 myX,尽管它说是 const。当我分配给 y 时,如何确保我的编译器抱怨? (Visual C++ 2008)
非常感谢!
【问题讨论】:
-
想象它是一个指针而不是一个引用。然后你可以看到
*y = newY仍然可以是 const,因为指针本身没有改变,只是指针。同样,引用没有改变(这是不可能的),只是它所指的。