2013-06-29 142 views
0

如何更改重載操作符以返回值而不是參考?更改重載操作符以返回值而不是參考

#include <iostream> 
using namespace std; 

class IntList 
{ 
private: 
    int list[1]; 
public: 
    IntList() {list[0] = 0;} 
    int& operator[] (const int index) {return list[index];} 
}; 

int main() 
{ 
    IntList list; 

    cout << list[0] << endl; 
    list[0] = 1; 
    cout << list[0] << endl; 
    return 0; 
} 
+1

擺脫& – aaronman

+0

導致列表[0] = 1;有編譯錯誤。 –

+1

這是因爲您正在嘗試分配值 – aaronman

回答

3
int operator[] (const int index){} 
^^^^^ 

只需卸下&。一旦你這樣做了,你就不能用它來爲數組元素賦值。返回參考和非參考

當你發現的時候operator []返回引用之間

差異,它可以在賦值的左邊使用。這是可能的,因爲當你通過引用返回時,返回值operator []是一個l值。引用被視爲l值,因爲您可以參考存儲在內存中並具有地址的變量。
operator []返回通過值的表達式list[0] = 1;將最終評價[#]的東西等,

1=1; 

哪個是不合邏輯,因爲1不是1-值,編譯器會生成診斷所述左操作數必須是一個l值。

[#]在標0假設元素的值是1

+0

謝謝,這個結果列表[0] = 1;斷。你能解釋我爲什麼嗎?我是新來的C++。 –

+0

@DavidTunnell:希望解釋。 –

1

你可以只取出&做到這一點,所以你必須
int operator[] (const int index){}
但是,正如你注意到的那樣,問題是你不能分配給它沒有編譯錯誤,因爲索引操作符不再返回一個l值。所以我認爲你應該考慮爲什麼你想返回一個值而不是參考。有可能你想要一個模式,其中索引操作符不能用於分配給對象,可能是某種只讀類型的對象。你的另一個選擇是有一個單獨的函數來設置它,因爲索引操作符不能再用於這樣做

0

在你的代碼示例中,你正在使用賦值,它要求你返回一個引用。

list[0] = 1; 
list.operator[](0) = 1; 
int& xref = list.operator[](0); 
(xref) = 1; // <-- changed the value of list element 0. 

既然你想操作[](INT指數)返回一個值,這將轉化:

int x = list.operator[](0); 
x = 1; <-- you changed x, not list[0]. 

如果你想操作[](INT指數)返回一個值,但也有列表[0] = 1還在工作,你將需要提供操作的兩個版本,以便編譯器能夠確定你想在一個給定的呼叫調用哪個行爲:

// const member, returns a value. 
int operator[] (const int index) const {return list[index];} 

// non const member, which returns a reference to allow n[i] = x; 
int& operator[] (const int index) {return list[index];} 

注他們必須分歧呃通過返回類型和成員 - 常量。

#include <iostream> 
using namespace std; 

class IntList 
{ 
private: 
    int list[1]; 
public: 
    IntList() {list[0] = 0;} 
    int operator[] (const int index) const { return list[index]; } 
    int& operator[] (const int index) {return list[index];} 
}; 

int main(int argc, const char** argv) 
{ 
    IntList list; 

    cout << list[0] << endl; 
    list[0] = 1; 
    int x = list[0]; 
    cout << list[0] << ", " << x << endl; 
    return 0; 
} 

工作演示:http://ideone.com/9UEJND