返回引用的Const方法

Max*_*xpm 15 c++ methods const class

class Foo
{
    int Bar;

    public:

    int& GetBar() const
    {
        return Bar;
    }
}
Run Code Online (Sandbox Code Playgroud)

GetBar是一种const方法吗?它实际上并没有改变任何东西,但它为"外部世界"提供了一种改变它的方法.

Jör*_*son 20

您的代码中有拼写错误,这可能是您的意思:

class Foo
{
    int Bar;

    public:

    int& GetBar() const
    {
        return Bar; // Removed the ampersand, because a reference is returned, not an address
    }
}
Run Code Online (Sandbox Code Playgroud)

不,这不合法.使用标记方法时const,不仅您承诺不会触及对象的任何内部状态,还承诺不会返回任何可用于更改对象状态的内容.非const引用可用于修改范围之外的Bar的值GetBar(),因此您暗示您不能保留承诺.

您必须将方法更改为非const,返回const引用,或Bar通过将其标记为豁免promise mutable.如:mutable int Bar;mutable关键字告诉该对象的逻辑常量性不依赖于状态的编译器Bar.然后你可以用它做任何你喜欢的事情.