0
我遇到了一個我的C++編程類項目的問題,並且由於今晚12點,我只剩下一個問題,這真的讓我發瘋。方括號運算符[]重載在MyString鏈表中類C++
這裏是我的代碼有問題的一部分:
MyString &StrList::operator[](int i){
MyString *temp = new MyString;
struct Node * ptr = list.head;
if (i == 0){
return *(MyString *)((list.head)->data);
}
else{
for (int index = 0; index == i; index++){
ptr = ptr->next;
}
temp = (MyString *)(ptr->data);
return *temp;
}
}
const MyString& StrList::operator[](const int i) const{
//return ((StrList&)*this)[i];
MyString *temp = new MyString;
struct Node * ptr = list.head;
if (i == 0){
return *(MyString *)((list.head)->data);
//return *temp;
}
else{
for (int index = 0; index == i; index++)
ptr = ptr->next;
temp = (MyString *)(ptr->data);
return *temp;
}
}
而且這裏的問題是:
//main.cpp
StrList s1 {5 4 3 2 1 0}
for(int i = 0; i < 6; i++)
cout<<s1[i]<<endl;
然而,所有的6個號碼打印出來是5,這是列表中的第一個元素。 任何人都可以指出這裏有什麼問題嗎?歡迎任何評論/意見/經驗!我真的需要在今晚12點之前解決這個問題,非常感謝,謝謝!
'for(int index = 0; index == i; index ++)'仔細看看這是幹什麼的。 –
當你在調試器中進行操作時會發生什麼? –
for循環的條件是錯誤的..你想索引!= i –