(旧问题已回答,我需要将两个 cpp 文件编译在一起。 已发布有关“默认构造函数”无限打印的新问题。)
我有三个文件。
node.h 使用构造函数、析构函数声明定义节点类,但我想将实际定义放入 node.cpp
class node{
private:
int i;
node *next;
public:
node();
node(int);
~node();
void setNode(int);
};
node.cpp 包含以下格式的构造函数/析构函数的定义。它还“#include “node.h””
node::node()
{
node::setNode(0);
cout<<"default constructor"<<endl;
node *next = new node;
}
node::node(int value)
{
node::setNode(value);
cout<<"value constructor"<<endl;
node *next = new node;
}
node::~node(){
cout<<"default destructor"<<endl;
delete next;
}
node::setNode(int value){
i = value;
}
在 nodelist.cpp 中,这是我现在的主要功能。 它包括“node.h”。 但是编译好像找不到构造函数和析构函数
g++ nodelist.cpp
/tmp/cc6PoQNR.o: In function `main':
nodelist.cpp:(.text+0x11): undefined reference to `node::node()'
nodelist.cpp:(.text+0x22): undefined reference to `node::~node()'
collect2: error: ld returned 1 exit status
谁能解释一下这是什么问题?
如果可能的话,也许可以详细说明这个问题背后我缺乏的一些知识。
谢谢大家。我需要一起编译 node.cpp 和 nodelist.cpp。
下一个问题是:
在我的 nodelist.cpp 中,我刚刚输入了
int main(){
node x;
return 0;
}
但它正在打印无限数量的“默认构造函数”。
最佳答案
node *next = 新节点;默认构造函数中的这一行将为要设置到下一个节点的节点调用另一个默认构造函数,这将调用另一个默认构造函数,它将...等等
在 nullptr 旁边设置 - 你不想一次分配多个节点
关于c++ - node.h/node.cpp/nodelist.cpp之间的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913062/