在C ++中从const成员函数修改引用成员 [英] Modifying reference member from const member function in C++
问题描述
我正在处理我的代码的const正确性,只是想知道为什么这个代码编译:
I am working on const-correctness of my code and just wondered why this code compiles:
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)
As far as I understand, f() is changing the object myX, although it says to be const. How can I ensure my compiler complains when I do assign to y? (Visual C++ 2008)
感谢很多!
推荐答案
您不会更改 X
中的任何变量。其实,你正在改变 _y
这是一个局外人对你的类。不要忘记:
Because you are not changing any variable in X
. Actually, you are changing _y
which is an outsider with respect to your class. Don't forget that:
y = newY;
正在将 newY
的值分配给 y
指向的变量,但不是引用它们自己。只有在初始化时,才考虑引用。
Is assigning the value of newY
to the variable pointed by y
, but not the references them selves. Only on initialization the references are considered.
这篇关于在C ++中从const成员函数修改引用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!