【问题标题】:"cannot convert 'SinglyLinkedList<int>::node*' to 'int*' in assignment compilation terminated due to -Wfatal-errors."“由于 -Wfatal 错误而终止的赋值编译中,无法将 'SinglyLinkedList<int>::node*' 转换为 'int*'。”
【发布时间】:2015-04-18 20:32:19
【问题描述】:

错误

t.cpp: 在构造函数 'SinglyLinkedList::SinglyLinkedList(T*, size_t) [with T = int]': t.cpp:29: 从这里实例化 第 51 行: 错误:无法将 'SinglyLinkedList::node*' 转换为 'int*' in 赋值编译由于 -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放在前面

标签: c++ c++98


【解决方案1】:

您正在尝试将 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 };

【讨论】:

    【解决方案2】:

    错误就行了

    lastNode->next = thisNode;
    

    错误是

    cannot convert 'SinglyLinkedList::node*' to 'int*' in assignment
    

    我可以看到thisNode 的类型为node*,并且从错误消息中我得出结论next 是int* 类型的成员变量。

    因此,要么该声明是错误的,要么您将node* 分配给next 的想法是错误的。

    关于你的第二个问题(这真的应该是一个不同的问题,而不是一次问两个问题),你可以给你的结构一个构造函数,或者升级到C++11 并做new node{*arr, nullptr}。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多