return 值 int& 和 const int& 之间的区别

Difference between return values int& and const int&

我有两个功能。

int& abc()
const int& abc() const

这两个函数有什么区别?我有一个带有 class 的源代码,其中定义了这两个函数。这两个函数不是因为它们有确切的定义而模棱两可吗?这两者到底有什么区别?

下面是一个简单的程序,展示了两者之间的区别:

#include <iostream>

using namespace std;

class Foo {
    int c;
    public:
    Foo() {
        c = 1;
    }
    int abc() {
        c++;
        cout << "non-const, c = " << c << endl;
        return c;
    }

    const int& abc() const {
        //c++; // compile-error, can't modify in a const function
        cout << "const, c = " << c << endl;
        return c;
    }
};

int main() {
    const Foo foo1;
    Foo foo2;

    int a = foo1.abc();
    int b = foo2.abc();

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    a++; b++;

    cout << "a = " << a << endl;
    cout << "b = " << b << endl;

    cout << foo1.abc() << endl;
    cout << foo2.abc() << endl;
}

输出为

const, c = 1
non-const, c = 2
a = 1
b = 2
a = 2
b = 3
const, c = 1
1
non-const, c = 3
3

第一个函数允许修改成员变量c,而第二个则不能。根据 const 条件调用适当的函数。

将一个函数与它的 const 合格版本配对是很常见的。例如,参见 operator[] 表示 std::vector

成员函数可以在其常量性中重载。所以,第二个成员函数重载了第一个成员函数。它们不是同一个函数。一个是 const,另一个不是。 这在声明 class 的常量对象时很有用。常量对象只能访问常量成员函数。因此,您为这种情况声明了一个 const 成员函数。

class MyClass {
    int nr;
    public:
       MyClass (int value) : nr (value) {}
       int& getNr () {return nr;} // this will be called by a non constant obj
       conts int& getNr () const {return nr;} // this one will be 
          // called by a constant object
}

int main () {
    MyClass foo (1);
    const MyClass bar (2);

    // Here int& getNr () {} will be called
    cout << foo.getNr () << endl; 

    // And here const int& getNr () const {} will be called
    cout << bar.getNr () << endl;

    return 0;
}