2016-08-05 54 views
0

在我的圖書館我有一個數組類:級陣列,在運營商投指針[]

template < class Type > 
class Array 
{ 
Type* array_cData; 
... 
Type& operator[] (llint Index) 
    { 
     if (Index >= 0 && Index < array_iCount && Exist()) 
      return array_cData[Index]; 
    } 
}; 

這是很好的,但如果我在棧中已經生成的類,如:

Array<NString>* space = new Array<NString>(strList->toArray()); 
checkup("NString split", (*space)[0] == "Hello" && (*space)[1] == "world"); 
//I must get the object pointed by space and after use the operator[] 

所以我的問題是:我可以得到對象array_cData沒有指定對象指出這樣的:提前

Array<NString>* space = new Array<NString>(strList->toArray()); 
checkup("NString split", space[0] == "Hello" && space[1] == "world"); 

謝謝! :3

-Nobel3D

+0

爲什麼使用'new'? – Jarod42

+1

當然,只需使用一個自動變量:'Array space(strList-> toArray());'。更好的是使用'std :: array'。 – user657267

+0

@ Jarod42 strList-> toArray()返回一個數組,我知道它會更好,當函數返回數組 *時,我想到改進-Nobel3D – Nobel3D

回答

0

的慣用方法是不具有指針:

Array<NString> space{strList->toArray()}; 
checkup("NString split", space[0] == "Hello" && space[1] == "world"); 

與指針,你必須取消對它的引用以某種方式

Array<NString> spacePtr = // ... 
spacePtr->operator[](0); // classical for non operator method 
(*spacePtr)[0]; // classical for operator method 
spacePtr[0][0]; // abuse of the fact that a[0] is *(a + 0) 

auto& spaceRef = *spacePtr; 
spaceRef[0]; 
0

做最簡單的事情是將指針轉換爲參考

Array<NString>* spaceptr = new Array<NString>(strList->toArray()); 

Array<NString> &space=*spaceptr; 

checkup("NString split", space[0] == "Hello" && space[1] == "world"); 

附:如果operator[]收到一個無效的索引值,您將收到一劑未定義的行爲,第二次幫助發生崩潰。

+0

當用戶調用operator [] -Nobel3D時,目標是自動執行此過程 – Nobel3D