can*_*rem 4 c++ overloading operator-keyword
我还是C++的新手,所以我每天遇到新问题.
今天来了[]运营商:
我正在使自己成为一个新的通用List类,因为我真的不喜欢std的那个.我试图给它C#的Collections.Generic列表的温暖和模糊的外观,所以我希望能够通过索引访问元素.切入追逐:
从模板中提取:
T& operator[](int offset)
{
int translateVal = offset - cursorPos;
MoveCursor(translateVal);
return cursor->value;
}
const T& operator[](int offset) const
{
int translateVal = offset - cursorPos;
MoveCursor(translateVal);
return cursor->value;
}
Run Code Online (Sandbox Code Playgroud)
这是运营商的代码.模板使用"模板",所以就我在一些教程中看到的那样,这是进行操作符重载的正确方法.
然而,当我试图通过索引访问时,例如:
Collections::List<int> *myList;
myList = new Collections::List<int>();
myList->SetCapacity(11);
myList->Add(4);
myList->Add(10);
int a = myList[0];
Run Code Online (Sandbox Code Playgroud)
我明白了
no suitable conversion function from "Collections::List<int>" to "int" exists
Run Code Online (Sandbox Code Playgroud)
错误,引用"int a = myList [0]"行.基本上"myList [0]"类型仍然是"Collections :: List",虽然它应该只是int.怎么会?
Ash*_*sha 14
由于myList指针myList[0]不会调用operator[],因此返回Collections::List<int>*.你想要的是什么(*myList)[0].或者更好,Collections::List<int>& myRef = *myList;然后使用myRef[0](其他选项不是myList在堆上分配内存,你可以在堆栈上创建它Collections::List<int> myList然后使用.运算符).