2008-11-23 57 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; 
}