我正在研究我的代码的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)
非常感谢!
我惊讶地发现"const"中的这个"漏洞":
#include <stdio.h>
class A
{
int r ;
public:
A():r(0){}
void nonconst()
{
puts( "I am in ur nonconst method" ) ;
r++;
}
} ;
class B
{
A a ;
A* aPtr ;
public:
B(){ aPtr = new A() ; }
void go() const
{
//a.nonconst() ; // illegal
aPtr->nonconst() ; //legal
}
} ;
int main()
{
B b ;
b.go() ;
}
Run Code Online (Sandbox Code Playgroud)
因此,基本上从const方法B::go(),如果指针引用了类型的对象,则可以调用非const成员函数(恰当地命名nonconst())A.
这是为什么?看起来像一个问题(它在我的代码中,我找到了它.)