方括号运算符[]在MyString链接列表类c+中重载+; 我遇到了一个C++编程类项目的问题,今晚12点到期,我只剩下一个问题,它真的让我发疯了。
以下是我的代码中有问题的部分:方括号运算符[]在MyString链接列表类c+中重载+; 我遇到了一个C++编程类项目的问题,今晚12点到期,我只剩下一个问题,它真的让我发疯了。,c++,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
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;
//main.cpp
StrList s1{5 4 3 2 1 0}
对于(int i=0;i<6;i++)
请仔细看看这个:
for (int index = 0; index == i; index++){
ptr = ptr->next;
}
那不应该是
for (int index = 0; index != i; index++){
ptr = ptr->next;
}
?for(int index=0;index==i;index++)
仔细看看这是怎么回事。在调试器中单步执行时会发生什么?for循环上的条件是错误的。。你想要索引!=iUnrelated:您从未使用在第一行中创建的MyString
。要么完全消除temp
,要么至少用nullptr
或NULL
或0
替换new MyString
。