从类中返回指针

blc*_*llo 2 c++ pointers linked-list

对于我的编程类,我必须编写一个链表类.我们必须包含的一个功能是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;
}
Run Code Online (Sandbox Code Playgroud)

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

luq*_*qui 7

Set*是正确的.你在这个功能中遇到了一个相当愚蠢的错误:

Set* Set::next() {
    Set *current;
    current = this;
    return current->next;
}
Run Code Online (Sandbox Code Playgroud)

最后一行应该是return current->nextval.否则你试图返回一个指向next函数的指针...可能不是你想要的东西.:-)


Mel*_*een 6

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

Set* Set::next() {
    return nextval;
}
Run Code Online (Sandbox Code Playgroud)