2017-07-14 71 views
-5

我有这个代码,我试图在两个不同的类中使用相同的模板。当我编译,我得到错误:为什么我不能为不同的课程使用相同的模板?

#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 { 
    ^
+0

'root.value'或'root-> value'? –

+0

'BST t class';你是从C来的吗? 1)这不是合法的C++,在一个不相关的说明中,你也不需要'struct',但它允许2)你需要指定模板参数 – Rakete1111

+0

至于你提出的错误,你*知道如何使用模板类?你用'Node'模板做到了吗?也许你应该退一步,并[找到一本好初学书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)来阅读? –

回答

5

您还没有指定的BST类型。 模板是一种不完整的类型,除非您相应地指定它。另一种选择是编译器可以以某种方式推断该类型。 否则它是一个不完整的类型 - 因此你得到一个错误。

如果你想例如int类型的树应该是:

BST<int> t; 
t.set_value(10); 
t.print_value(); 

注意,你不需要class关键字来声明t

+0

问题是,我不能定义类型作为模板用于通用数据类型的权利?所以如果我打算最终使用BST 作为整数树,那么模板的用法是什么? –

+1

模板是一个类的蓝图。你可以用它来写出许多具有相同行为的不同类。 'BST intTree'是一棵只包含整数的树,'BST stringTree'将包含字符串。然而'intTree'不能存放字符串,'stringTree'也不能存放整数。这根本不是模板的目的。 – muXXmit2X

+0

很酷。有道理:)谢谢.. :) –

相关问题