获取模板错误。在此范围内未声明"T"

Getting template error. 'T" was not declared in this scope

本文关键字:范围内 未声明 错误 获取      更新时间:2023-10-16

我只是在练习使用模板的最佳程序。程序如下:

template<class T>
class bstnode
{
    public: 
        T key;
        bstnode *left, *right;
        bstnode()
        {
            left=right=0;
        }
        bstnode(const T& el, bstnode *l=0, bstnode *r=0)
        {
            key=el;
            left=l;
            right=r;
        }
};
template<class T>
class bst
{
    protected:
        bstnode<T>* root;
    public:
        bst()
        {
            root=0;
        }
        void insert(T);
        void display();
        void inorder(bstnode<T> *);
};
void inorder(bstnode <T>* b1)  //ERROR 'T' was not declared in scope
{
    if(b1)
    {
        cout<<b1->key;
    }
    else
    {
        return;
    }
    inorder(b1->right);        
    inorder(b1->left);
}
template<class T>
void bst<T>::display()
{
    //bstnode<T> * b=new bstnode<T>();
    //b=root;
    inorder(root);  
}
template<class T>
void bst<T>::insert(T v)
{
    bstnode<T>* b=new bstnode<T>();
    b->key=v;
    if(root==NULL)
    {
        root=b;
    }
    else
    {
        bstnode<T>* temp=root;
        while((temp->left!=NULL)||(temp->right!=NULL))
        {
            if(temp->key > b->key)
            {
                temp=temp->right;
            }
            else
            {
                temp=temp->left;
            }
        }
        if(temp->key < b->key)
        {
            temp->left=b;
        }
        else
        {
            temp->right=b;
        }   
    }
}
int main(int argc, char *argv[])
{
    bst<int>b;
    b.insert(10);
    b.insert(5);
    b.insert(2);
    return 0;
}

在编译过程中,我得到错误'T'没有在inorder函数的作用域中声明。

请帮我解决这个问题。

你必须写

template <typename T>
void bst<T>::inorder(bstnode <T>* b1)  
{
    if(b1) cout<<b1->key;
    else return;
    inorder(b1->right);        
    inorder(b1->left);
}

由于inorder函数位于类体之外,因此需要添加另一个模板,该模板在

类之外引用inorder。
template<class T>