我有这个代码,我试图在两个不同的类中使用相同的模板。当我编译,我得到错误:为什么我不能为不同的课程使用相同的模板?
#include <iostream>
#include <memory>
template <class T>
class Node
{
public:
int value;
std::shared_ptr<Node> leftPtr;
std::shared_ptr<Node> rightPtr;
Node(int val) : value(val) {
std::cout<<"Contructor"<<std::endl;
}
~Node() {
std::cout<<"Destructor"<<std::endl;
}
};
template <class T>
class BST {
private:
std::shared_ptr<Node<T>> root;
public:
void set_value(T val){
root->value = val;
}
void print_value(){
std::cout << "Value: " << root.value << "\n";
}
};
int main(){
class BST t;
t.set_value(10);
t.print_value();
return 1;
}
错误:
g++ -o p binary_tree_shared_pointers.cpp --std=c++14
binary_tree_shared_pointers.cpp:39:8: error: elaborated type refers to a template
class BST t;
^
binary_tree_shared_pointers.cpp:21:7: note: declared here
class BST {
^
'root.value'或'root-> value'? –
'BST t class';你是从C来的吗? 1)这不是合法的C++,在一个不相关的说明中,你也不需要'struct',但它允许2)你需要指定模板参数 – Rakete1111
至于你提出的错误,你*知道如何使用模板类?你用'Node'模板做到了吗?也许你应该退一步,并[找到一本好初学书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)来阅读? –