c++ - "cannot convert ' 单链表<int>::节点* ' to ' int* ' in assignment compilation terminated due to -Wfatal-errors."

标签 c++ c++98

错误

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/

相关文章:

c++ - 使用 gmock 返回模拟方法参数

c++ - 为什么用大括号 init 初始化对象是合法的,即使它不是聚合?

c++ - boost::作为友元类的变体

c++ - 如何将 int 对 vector 的默认值设置为空?

c++ - 为什么大型本地数组会使我的程序崩溃,而全局数组却不会?

c++ - MPI 程序只捕获来自等级 1 的消息

c++ - 哪个熵更高?

c++ - 错误: expected primary-expression before ']' token in C++

c++ - 为什么将语言标准从 -std=gnu++98 提升到 -std=gnu++11

c++ - 在一个类中声明另一个类的成员(它接受一个参数)?