方括号operator []在MyString链表c ++中重载

时间:2013-12-11 00:59:24

标签: c++

我遇到了我的c ++编程类项目的问题,今晚12点到了,我只剩下一个问题了,这真让我疯狂。

这是我的代码中有问题的一部分:

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点前解决这个问题,非常感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

仔细看看:

    for (int index = 0; index == i; index++){
        ptr = ptr->next;
    }

不应该是......

    for (int index = 0; index != i; index++){
        ptr = ptr->next;
    }