2

对于我的编程课,我必须编写一个链表类。我们必须包含的函数之一是 next()。该函数将返回列表中下一个元素的内存地址。

#include <iostream>
using namespace std;

class Set {
    private:
        int num;
        Set *nextval;
        bool empty;
    public:
        Set();
        <some return type> next();
};

<some return type> Set::next() {
    Set *current;
    current = this;
    return current->next;
}

int main() {
    Set a, *b, *c;
    for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question

    // Test the next_element() iterator
    b = a.next();
    c = b->next();
    cout << "Third element of b = " << c->value() << endl;

    return 0;
}

如您所见,我需要将指针设置为保存列表*b*c下一个元素的内存地址。我的问题是我会使用什么样的返回类型?我试过用 Set 和 Set* 代替但得到编译器错误。任何帮助是极大的赞赏。

4

2 回答 2

7

Set*是正确的。您在此功能中遇到了一个相当愚蠢的错误:

Set* Set::next() {
    Set *current;
    current = this;
    return current->next;
}

最后一行应该是return current->nextval. 否则,您将尝试返回指向该next函数的指针……可能永远都不是您想要的。:-)

于 2008-11-23T08:07:27.730 回答
6

luqui 是正确的,虽然你的下一个函数过于复杂,但没有理由复制this指针,这很愚蠢。改用这个:

Set* Set::next() {
    return nextval;
}
于 2008-11-23T08:12:59.777 回答