c ++类与模板无法找到其构造函数 [英] c++ class with template cannot find its constructor

查看:192
本文介绍了c ++类与模板无法找到其构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我真的不明白。我有一个类Node。

I have a problem I don't really understand. I have a class Node.

template<class T>
class node {
protected:
    T _data;
public:
    node(T data);	
};

这是在node.h文件中。在node.cpp文件中,有这个构造函数:

This is in "node.h" file. In "node.cpp" file, there is this constructor:

#include "node.h"

template<class T>
node<T>::node (T data) {
    _data = data;
}

当编译器没有发现错误时,链接器(ld)告诉我: / p>

While the compiler finds no error, the linker (ld) tells me:



/ usr / bin / ld:未定义符号:

/usr/bin/ld: Undefined symbols:

节点< int> :: node(int)

node<int>::node(int)


如果我将构造函数从.cpp移动到.h文件,一切工作正常。问题在哪里?

the weird part... if I move the constructor from .cpp to .h file, everything works fine. Where is the problem?

推荐答案

问题是模板不是类 - 你通常不会在两个单独的文件。模板类是编译器用于生成类的代码。因此,您的实现代码需要有效地内联,即在您发现的标头中。

The problem is that templates aren't classes - you don't normally write them in two separate files. Template classes are code that the compiler uses to generate classes. As such, your implementation code needs to effectively be inline, i.e., in the header as you discovered.

有关为什么的更全面的解释必须采用这种方式,请参阅 C ++常见问题解答Lite

For a fuller explanation of why it has to be this way, see the C++ FAQ Lite.

这篇关于c ++类与模板无法找到其构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆