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

时间:2010-03-12 09:25:17

标签: c++ reference const

我正在研究我的代码的const-correctness,并且想知道为什么这段代码会编译:

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)

非常感谢!

3 个答案:

答案 0 :(得分:23)

因为您没有更改X中的任何变量。实际上,你正在改变_y,这是一个与你的班级有关的局外人。别忘了:

y = newY;

newY的值分配给y指向的变量,而不是它们自己引用的变量。仅在初始化时才考虑引用。

答案 1 :(得分:5)

情况类似于指针成员。在const成员函数中,const适用于指针本身,而不是指针对象。

区别在于:

X* const //this is how the const applies: you can modify the pointee
const X*

除了X& const不是有效的语法,因为不能引用引用首先引用另一个对象(它们隐式总是const)。总之:const on methods对成员引用没有影响。

答案 2 :(得分:0)

我想说,作为已接受答案的其他信息,实际上 更改X中的变量。

  

因为您没有在X中更改任何变量。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Bar {
public:
    void funcA() const {
        c++;
    }

    int b = 3;
    int &c = b;
};

int main()
{
    Bar b;
    b.funcA();
    cout << b.b << endl;  //4
}

因此,此问题的主要思想是:

  

它修改成员所指的内容,而不修改成员。

这也适用于指针成员。

在此处查看Why can reference members be modified by const member functions?

相关问题