2016-08-05 60 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