【问题标题】:class array, cast pointer in operator[]类数组,在 operator[] 中转换指针
【发布时间】:2016-08-05 02:08:13
【问题描述】:

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

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&lt;NString&gt; space(strList-&gt;toArray());。更好的是使用std::array
  • @Jarod42 strList->toArray() 返回一个 Array,我知道函数返回 Array* 会更好,我想改进 -Nobel3D
  • 它返回Array&lt;NString&gt; 似乎比通过指针更好,但是你需要指针吗?
  • 是的,当用户调用操作员时,我只想调用 'space[0]',而 'space' 是一个指针 -Nobel3D

标签: c++ arrays c++11 casting operator-overloading


【解决方案1】:

惯用的方法是没有指针:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 目标是在用户调用 operator[] -Nobel3D 时自动执行此过程
    猜你喜欢
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    相关资源
    最近更新 更多