2015-07-11 185 views
-2

我有兩個函數。返回值之間的區別int&和const int&

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

這兩個函數有什麼區別?我有一個裏面定義了這兩個函數的類的源代碼。這兩個功能不是模棱兩可的,因爲它們有確切的定義?這兩者之間的區別究竟是什麼?

+3

_「這兩者之間究竟有什麼區別?」 - 一個是const限定的,另一個不是。 –

+0

您沒有向我們展示函數的定義,並且在任何情況下,函數的定義都不會影響重載解析。 –

+0

當兩個函數具有相同的確切定義時,它們如何超載? –

回答

2

下面是一個簡單的程序展示在兩者之間的區別是:第一功能被允許修改成員變量c

#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 

,而第二個不能。根據const資格認證調用適當的功能。

通常具有與const合格版本配對的功能。例如,請參見operator[],關於std::vector

相關問題