使用模板构造函数创建模板类对象 [英] Creating a template class object using a template constructor
问题描述
我无法从模板类创建类对象,在该类中,我需要构造函数也应作为模板并在创建对象时接受参数。但是,当我尝试创建对象时,收到一条错误消息,指出我所引用的不存在。
I'm having trouble creating a class object from a template class in which I need the constructor to also be a template and accept a parameter when the object is created. However, when I attempt to create the object, I receive an error message stating that I'm referencing something that doesn't exist.
这是我的代码:
using namespace std;
#include <cstdlib>
template <class Node_Type>
class BinaryTree
{
public:
BinaryTree(Node_Type);
BinaryTree(Node_Type, Node_Type);
BinaryTree(Node_Type, Node_Type, Node_Type);
bool isEmpty();
Node_Type info();
Node_Type inOrder();
Node_Type preOrder();
Node_Type postOrder();
private:
struct Tree_Node
{
Node_Type Node_Info;
BinaryTree<Node_Type> *left;
BinaryTree<Node_Type> *right;
};
Tree_Node *root;
};
#endif
和我的.cpp:
template <class Node_Type>
BinaryTree<Node_Type>::BinaryTree(Node_Type rootNode) {
root = rootNode;
root->left = NULL;
root->right = NULL;
}
.cpp还有更多功能,但这只是其他功能无关的成员。上面显示的构造函数是我无法使用的。
There's more to the .cpp, but it's just other function members that are irrelevant. My constructor shown above is what I can't get to work.
在我的主机中,我试图通过调用声明我的对象:
In my main, I'm attempting to declare my object with the call:
BinaryTree<char> node('a');
但是当我尝试这样做时,我收到一条错误消息,指出:
but when I try this, I get an error message stating:
undefined reference to `BinaryTree<char>::BinaryTree(char)'
我已经尝试了两天。我已经搜寻了所有我能想到的主题,并且在没有帮助的情况下阅读了关于Stack Overflow和其他资源的无数示例。谁能解释我的问题是什么?我知道该怎么做,如果语法在C ++中不是那么荒谬,我现在就结束了。
I've been trying to figure this out for two days now. I've Googled every topic I can think of and read countless examples on Stack Overflow and other sources with no help. Can anyone please explain what my problem is? I know how to do my project, and I'd be finished by now if the syntax wasn't so ridiculous in C++. Thanks in advance!
推荐答案
模板代码在实例化时应该可见,这意味着函数的定义也必须是在标题中。
Template code should be visible at the time of instantiation, meaning that the definition of the functions must also be in the header.
这篇关于使用模板构造函数创建模板类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!