Phi*_*ipp 24 c++ const reference
我正在研究我的代码的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);
...
}
Run Code Online (Sandbox Code Playgroud)
据我所知,f()正在改变对象myX,尽管它说是const.当我分配给y时,如何确保我的编译器抱怨?(Visual C++ 2008)
非常感谢!
Ara*_*raK 23
因为你没有改变任何变量X.实际上,你正在改变_y哪个是关于你班级的局外人.别忘了:
y = newY;
Run Code Online (Sandbox Code Playgroud)
将值newY赋给指向的变量y,而不是它们自己的引用.仅在初始化时才考虑引用.
情况类似于指针成员.在const成员函数中,const适用于指针本身,而不是指针.
这是区别:
X* const //this is how the const applies: you can modify the pointee
const X*
Run Code Online (Sandbox Code Playgroud)
除了X& const不是有效的语法,因为不能引用引用首先引用另一个对象(它们隐式总是const).总之:const on methods对成员引用没有影响.
| 归档时间: |
|
| 查看次数: |
2709 次 |
| 最近记录: |