错误
t.cpp: In constructor 'SinglyLinkedList::SinglyLinkedList(T*, size_t) [with T = int]': t.cpp:29: instantiated from here Line 51: error: cannot convert 'SinglyLinkedList::node*' to 'int*' in assignment compilation terminated due to -Wfatal-errors.
在如下所示的行中
node * lastNode = new node;
lastNode->val = *arr;
lastNode->next = NULL;
for (T * pa(arr+1), * pb(arr+n); pa != pb; ++pa)
{
node * thisNode = new node;
thisNode->val = *pa;
thisNode->next = NULL;
lastNode->next = thisNode; // error
lastNode = thisNode;
delete thisNode;
}
完整代码在这里:http://codepad.org/gZ2KnrUM
无法找出该行在语法上不正确的地方。
额外的问题:有没有一种方法可以用 new
简化 struct
的初始化?我希望能够像这样制作线条
node * lastNode = new node;
lastNode->val = *arr;
lastNode->next = NULL;
如果可能,成一行。我知道如果我在堆栈上创建它那么我可以做
node lastNode = { *arr, NULL m};
但是对于使用 new
创建是否有等效的大括号初始化?
最佳答案
您正在尝试将 node *
类型分配给 int *
类型的变量。
你的节点代码应该是:
struct node
{
T val;
node * next;
};
至于“速记初始化”,我只会使用构造函数。
class node
{
T val;
node * next;
public:
node(T val, node * next)
: this->val(val)
, this->next(next)
{};
};
node * lastNode = new node(*arr, nullptr);
或者一个c++11初始化器:
node * lastNode = new node { *arr, nullptr };
关于c++ - "cannot convert ' 单链表<int>::节点* ' to ' int* ' in assignment compilation terminated due to -Wfatal-errors.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29722517/