C ++:尝试在模板化的类中声明和定义模板化的类。我的代码出了什么问题?

时间:2015-01-06 21:12:22

标签: c++ templates

#ifndef SIMPLE_BST_HPP
#define SIMPLE_BST_HPP

#include <vector>

template <class T>
class SimpleBST {

public:

    SimpleBST(std::vector<T>);


    template <class T>
    class BSTNode
    {


    };

};


#endif

但是,编译时出现此错误:

In file included from SimpleBST.cpp:1:0:
SimpleBST.hpp:14:12: error: declaration of ‘class T’
  template <class T>
            ^
SimpleBST.hpp:6:11: error:  shadows template parm ‘class T’
 template <class T>
           ^
In file included from main.cpp:1:0:
SimpleBST.hpp:14:12: error: declaration of ‘class T’
  template <class T>
            ^
SimpleBST.hpp:6:11: error:  shadows template parm ‘class T’
 template <class T>
           ^

有谁知道为什么我无法定义BSTNode?我最终将节点设为私有,但此时,我只是想在SimpleBST中声明一个类,它可以用作存储二叉搜索树元素的基本节点。

谢谢!

1 个答案:

答案 0 :(得分:1)

考虑到您正在创建的类,使用嵌套类的类模板没有意义。

您不希望SimpleBST<double>包含BSTNode<int>

BSTNode下将SimpleBST<T>设为简单的嵌套类型。

template <class T>
class SimpleBST {

public:

    SimpleBST(std::vector<T>);

    class BSTNode
    {
    };

};