Modifying reference member from const member function in C++(从 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 成员函数修改引用成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ 中的 const 成员函数修改引用成员
基础教程推荐
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
