【问题标题】:C++ use struct defined in another caused endless loopC++ 使用 struct 中定义的另一个导致无限循环
【发布时间】:2014-01-12 23:28:38
【问题描述】:

这是名为Node.h的头文件。

struct node{
    int val;
    node *next;
    node(int x){
    val = x;
    next = NULL;
};

void test(){
    node *head = new node(1);
    head->next = new node(1);
    head->next->next = new node(2);
    cout<<head->val;
};

我有一个Test.cpp 文件,我在其main 函数中调用了test()

#include "Node.h"
int main(){
    test();
    return 0;
}

输出是 lldb 而不是节点的值,应该是 1。

【问题讨论】:

  • 你怎么知道这是一个无限循环?你调试过吗?向node 构造函数添加了日志记录?出现问题时,请按原样粘贴两个文件。
  • 显然主要问题是在你没有显示的代码中。请发布一个完整但最小的示例,供读者编译和测试,以举例说明问题。如果需要两个源代码文件,把两者的源代码贴出来。
  • 顺便说一句,在构造函数定义的结束 } 之后有一个多余的分号。从技术上讲,这是错误的,但可能会被接受(可能带有警告)。只需将其删除。
  • 上面的代码无法编译。
  • @– 干杯和hth。 - Alf 我认为是第 7 章说声明可以为空。

标签: c++


【解决方案1】:

正如上面某些 cmets 中所述,您的代码无法编译。

首先,在您包含某些头文件之前,不会声明 NULL,例如cstddef (见NULL is not declared)。 您还必须包含iostream 标头才能使用cout。最后,您错过了 Node.h 中的一个闭合大括号 }。在这些更正之后,程序会按预期输出 1。

这是编译的头文件:

#include <cstddef>
#include <iostream>

struct node
{
  int val;
  node *next;
  node(int x)
  {
    val = x;
    next = NULL;
  } //was missing
};

void test()
{
  node *head = new node(1);
  head->next = new node(1);
  head->next->next = new node(2);
  std::cout<<head->val;
};

【讨论】:

    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2020-08-27
    • 2021-05-07
    相关资源
    最近更新 更多