类数组,在运算符[]中强制转换指针
class array, cast pointer in operator[]
在我的库中,我有一个数组类:
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[]
接收到无效的索引值,您将获得未定义行为的剂量,以及崩溃的第二次帮助。
相关文章:
- 转换指针引用的字符串
- 无法向上转换指针到指针参数
- 混合转换指针和引用
- 堆栈对象的强制转换指针
- 基类到派生模板类的强制转换指针,而不知道类型
- 删除类型转换指针的最佳方法
- 管理到本机值类转换:强制转换指针是否安全?
- 转换指针类型
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 当我们递增下面的类型转换指针时会发生什么?
- 类型强制转换指针构造函数调用
- 如何转换(指针向量)-->(指向指针数组的指针)
- 如何从类功能转换指针
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- Delphi中的类型转换指针添加
- C++分段错误(核心转储)错误 - 强制转换指针/将函数值返回到线程
- 以C++和运算符优先级键入指向数组成员的强制转换指针
- C++动态强制转换指针的内存清理
- 转换指针和引用的好处
- 在c++中转换指针