类数组,在运算符[]中强制转换指针

class array, cast pointer in operator[]

本文关键字:转换 指针 数组 运算符      更新时间:2023-10-16

在我的库中,我有一个数组类:

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

惯用的方法是没有指针:

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];

最简单的方法是将指针转换为引用

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

附言:如果operator[]接收到无效的索引值,您将获得未定义行为的剂量,以及崩溃的第二次帮助。