2

だから私はC ++でミルリンクリストの実行を実装しようとしています

template<class T>
class Node
{
private:
    Node *next;
    T item;

public:
    Node(T item)
        : item(item)
    {
        this->next = NULL;
    }

    Node<T> add(T item) {
         this->next = new Node(item);
         return *this->next;
    }

    bool hasNext()
    {
        return this->next == NULL;
    }

    Node<T> getNext()
    {
        return *this->next;
    }

    T value()
    {
        return this->item;
    }
};

void main()
{
    Node<int> node(3);
    node.add(3).add(4);

    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();

    cin.get();
}

しかし、私はそれを機能させることができません。特にこのセクション:

    node.add(3).add(4);

    cout << node.value();
    cout << node.getNext().value();
    cout << node.getNext().getNext().value();

add関数と関数をの代わりにgetNext返すように変更すると、正常に動作します。しかし、逆参照によってコードが破損するのはなぜでしょうか? 表記は よりも理にかなっていると思いますが、機能させることができません。私は何を間違っていますか?Node<T>*Node<T>.->

4

1 に答える 1

7

現在、作成した実際のノードを返すのではなく、追加したノードのコピーを作成しています。かっこは、後であなたのコードを見なければならない他の人に少しわかりやすくするだけです。add 関数は次のように変更する必要があります。

Node<T>& add(T item) {
     this->next = new Node(item);
     return *(this->next);
}

または、新しく作成されたノードへのポインターを返すこともできますが、これは main.ではなくを使用して壊れます。->

また、同様の変更を行う必要がありますnext()

于 2013-05-09T15:55:44.427 に答える