错误
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创建是否有等效的括号初始化?
创建节点的捷径将是使用与以前相同的语法,但在其前面放置new node
您正在尝试将类型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 };
哎呀! 我打-o ..对不起。
错误就在网上
lastNode->next = thisNode;
错误是
cannot convert 'SinglyLinkedList::node*' to 'int*' in assignment
我可以看到thisNode的类型为node*,从错误消息中我可以得出结论,next是类型为int*的成员变量。
因此,该声明是错误的,或者您将node*分配给next的想法是错误的。
关于第二个问题(实际上应该是一个不同的问题,而不是一次问两个问题),您可以为您的struct提供一个构造函数,或者升级到C++11并执行new node{*arr, nullptr}。