相关疑难解决方法(0)

在C++中修改const成员函数的引用成员

我正在研究我的代码的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)

非常感谢!

c++ const reference

24
推荐指数
2
解决办法
2709
查看次数

标签 统计

c++ ×1

const ×1

reference ×1