gpt4 book ai didi

C++ 未定义对链接函数的引用

转载 作者:太空宇宙 更新时间:2023-11-04 14:06:47 24 4
gpt4 key购买 nike

我在链接 C++ 项目时遇到问题,我无法弄清楚哪里出了问题。代码的笑话。

客户端.cpp

#include <iostream>
#include "node.h"
using namespace std;

int main(int argc, char** argv)
{
node<int> *ndNew = new node<int>(7);
return 0;
}

节点.h

#ifndef NODE_H
#define NODE_H
#include <vector>

template <typename T>
class node
{
private:
node<T>* ndFather;
std::vector<node<T>* > vecSons;
public:
T* Data;
node(const T &Data);
};
#endif

节点.cpp

#include "node.h"

using namespace std;

template <typename T>
node<T>::node(const T &Data)
{
this->Data = &Data;
this->ndFather = 0;
this->vecSons = (new vector<T>());
};

使用的编译命令是

g++ -Wall -g clitest.cpp node.cpp -o clitest

错误日志是这样的

clitest.cpp: In function ‘int main(int, char**)’:
clitest.cpp:8:16: warning: unused variable ‘ndNew’ [-Wunused-variable]
node<int> *ndNew = new node<int>(7);
^
/tmp/cc258ryG.o: In function `main':
clitest.cpp:8: undefined reference to `node<int>::node(int const&)'
collect2: error: ld returned 1 exit status
make: *** [blist] Error 1

我花了相当多的时间来修改代码,试图找出问题所在,但我要么遗漏了一些基本的东西,要么就是我对 C++ 链接一无所知。

最佳答案

使用模板时,编译器需要知道如何在实例化类时为类生成代码。 undefined reference 错误是由于编译器没有生成node<int>::node(int const &)引起的构造函数。看,例如Why can templates only be implemented in the header file?

你有几个选择:

  1. 将实现放在 node.h 中(node.cpp 已删除,因为不需要)
  2. 将实现放在 node.h 底部#included 的文件中(通常该文件称为 node.tpp)

我建议将实现放在 node.h 中并删除 node.cpp。请注意,您的示例中的代码不是有效的 c++:成员变量 vecSons 不是指针,因此行 vecSons = new vector<T>()会给出编译器错误。以下代码可以作为完整实现的起点:

#ifndef NODE_H
#define NODE_H
#include <vector>

template <typename T>
class node
{
private:
node<T>* ndFather;
std::vector<node<T>* > vecSons;
public:
const T* Data;
node(const T &d) :
ndFather(0),
vecSons(),
Data(&d)
{
}
};
#endif

关于C++ 未定义对链接函数的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16550853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com