我想重載我的類中的下標運算符[],它使用鏈表創建一個映射。這和幾個變化,如添加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'的局部變量或全局變量。 –