2008-11-23 150 views
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 *替换成编译器错误。任何帮助是极大的赞赏。

回答

7

Set*是正确的。您是从一个相当愚蠢的错误在这个函数的痛苦:

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

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

6

luqui是正确的,虽然你的下一个功能过于复杂,没有理由复制指针,这只是愚蠢。改为:

Set* Set::next() { 
    return nextval; 
}