C ++ - 通过流添加结构,这段代码有什么问题?

时间:2016-02-18 20:10:23

标签: c++ pointers struct stream

我正在练习C ++中的流程,因为我在学校里有一个期中考试。我正在尝试编写一个小程序,将项添加到节点列表(结构)。我已经获得了以下代码,并且收到了明显错误,但不知道如何修复它。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

struct Node {  
    string name;
    Node *next;
};

void foo(istream &in, ostream &out, Node *list) {
    string nom;
    in >> nom;                     //Assigns value to nom via cin
    Node *temp = list;

    while (temp->next != NULL) {   //Loops through list to find null pointer
        temp = temp->next;            //to add new Node to
    }

    Node item;                     //Creates new Node with a NULL next
    item.name = nom;
    item.next = NULL;
    temp->next = item;             //Adds item to the list
    out << nom;                    //Outputs that it's been added
    cout << " added" << endl;
}

int main() {
    Node one;
    one.next = NULL;  
    foo(cin, cout, &one);
}

我得到的错误是:

Cannot convert 'Node' to 'Node*' in assignment (Line 22)

1 个答案:

答案 0 :(得分:1)

除了类型不匹配(NodeNode*不相同)之外,您没有动态分配item,并且当foo完成时它将被销毁。分配&item会使您无效temp->next

在代码中:

Node *item = new Node;
item->name = nom;
item->next = nullptr; // I can't write NULL
temp->next = item; 

浓缩成一个陈述:

temp->next = new Node{nom, nullptr};