我想重载我的类中的下标运算符[],它使用链表创建一个映射。这和几个变化,如添加const,就是我所尝试过的。C++ overload []运算符
头
int& operator[](std::string key);
然后定义在一个单独的文件
int& mapLL::operator[](std::string key){
int val = this->get(key);
return val;
}
这个过载是我不知道如何解决
main.cpp: In function ‘int main()’:
main.cpp:38:24: error: invalid types ‘mapLL*[const char [4]]’ for array subscript
int a = list3["ghi"];
^
mapLL.cpp: In member function ‘int& mapLL::operator[](std::string)’:
mapLL.cpp:110:9: warning: reference to local variable ‘val’ returned [-Wreturn-local-addr]
int val = this->get(key);
^
然后在错误主要文件我正在尝试这个
mapLL *list3 = new mapLL();
list3->set("abc",1);
list3->set("def",2);
list3->set("ghi",3);
list3->set("jkl",1);
list3->toString();
cout << list3->get("ghi") << endl;
int a = list3["ghi"];
cout << a << endl;
delete list3;
get函数
int mapLL::get(std::string key){
bool found = false;
node *me = (node *) first;
if(is_empty()){
return -2;
}
while(!found){
if (me->getKey() == key){
return me->getValue();
}else{
if (me->getNext() == 0){
return -1;
}else{
me = (node *) me->getNext();
}
}
}
}
它看起来像'list3'是一个指针,所以你就必须做'(*项目list3) “GHI”]' – Brian
此外,由于编译器警告你该方法返回一个临时引用。这绝对不是你想要做的。 – Jon
是否有理由需要使用动态内存分配(例如,新操作符)?这不是Java或C#。你可以将'list3'声明为不带'new'的局部变量或全局变量。 –