2017-05-07 41 views
0

使用,看起來像一個功能:層疊函數調用

IntegerSet &insert(int m); 

我試圖創建一個支持級聯該值插入對象的數組調用的函數。

我的功能:

IntegerSet &IntegerSet::insert(int m) { 
    IntegerSet newObj; 
    for (int i = 0; i < 256; i++) { 
     newObj.set1[i] = set1[i]; //copy the array into the new object 
    } 
    newObj.set1[m] = true; 
    return newObj; 
} 

被返回的對象是空的,我懷疑有參考做。

試圖通過改變&改變它看起來像

IntegerSet IntegerSet::&insert(int m) 

使得它拒絕編譯,因爲它預計的標識符「。

+6

你返回到本地變量的引用。也許你可以擴展你的例子來包含IntegerSet的定義和你實際使用它的方式。您應該閱讀此:https://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable –

回答

3

這可能是你爲了使流暢的語法工作打算是什麼:

IntegerSet& IntegerSet::insert(int m) 
{ 
    this->set1[m] = true; 
    return *this; 
} 

對於精通語法,你通常需要大量的叫同一個對象,而不是臨時對象的增殖在成員函數。

1

您不應該返回對本地的引用,因爲它在函數返回時已經被銷燬。但是,您可能需要修改IntegerSet,您可以撥打insert,並返回對*this的引用。這比每次複印更有效率。

IntegerSet &IntegerSet::insert(int m) { 
    set1[m] = true; 
    return *this; 
} 

這種方式可以鏈功能的IntegerSet對象調用像這樣:

iset.insert(1).insert(2).insert(3);