简体   繁体   English

错误:“模板”之前的预期主表达式

[英]error: expected primary-expression before 'template'

Alright, so I'm trying to make a (for now) unbalanced binary tree. 好的,所以我正在尝试制作(暂时)不平衡的二叉树。 I'm getting a weird error that I can't seem to get rid of. 我收到一个似乎无法消除的奇怪错误。 The second half had the same error so I just got rid of it for now. 下半部分有相同的错误,所以我现在才摆脱它。

    void insert( binTreeNode < T >*& node, const T& obj) { // private version of insert( )
    if (obj < node->data) {
        if(node->left != NULL)
            insert(node->left, obj);
        else {
            binTreeNode<T> n;
            n = new binTreeNode(obj, NULL, NULL);
            node->left = n;
        }
    } else {
        if(node->right != NULL)
            insert(node->right, obj);
        else {

        }
    }
}

And the error 和错误

In file included from ../src/binTree.cc:2:0:
../src/binTree.h: In member function 'void binTree<T>::insert(binTreeNode<T>*&, const T&)':
../src/binTree.h:54:16: error: expected type-specifier before 'binTreeNode'
../src/binTree.h:54:16: error: expected ';' before 'binTreeNode'
src/subdir.mk:24: recipe for target `src/binTree.o' failed
make: *** [src/binTree.o] Error 1

binTreeNode's constructor is defined as binTreeNode的构造函数定义为

binTreeNode (const T& obj, binTreeNode < T >* leftObj = NULL, binTreeNode < T >* rightObj = NULL) {
    left = leftObj;
    right = rightObj;
    data = obj;
}

Thanks for your help. 谢谢你的帮助。

        n = new binTreeNode(obj, NULL, NULL);

Should be 应该

        n = new binTreeNode<T>(obj, NULL, NULL);

(also, n should be a pointer). (同样,n应该是一个指针)。

Classes don't autodeduce template parameters from constructors even when it's unambiguous. 即使类是明确的,类也不会从构造函数中自动推导出模板参数。 I'm not sure why. 我不知道为什么。 Maybe it's so that the code doesn't become brittle if you add another constructor. 也许是这样,如果添加另一个构造函数,代码不会变得很脆弱。

Anyway, if this really bugs you, you can always add a helper function: 无论如何,如果这确实使您感到烦恼,则可以随时添加一个辅助函数:

template<typename T>
binTreeNode<T>* newBinTreeNode(const T& obj, binTreeNode<T>* left, binTreeNode<T>* right) {
  return new binTreeNode<T>(obj, left, right);
}

You must precede the definition of insert() with the template<..> prefix when defining a member function outside of the class declaration: 在类声明之外定义成员函数时,必须在insert()的定义之前加上template<..>前缀:

template <typename T>
void binTree<T>::insert(binTreeNode < T >*& node, const T& obj) {
    if (obj < node->data) {
            if(node->left != NULL)
                insert(node->left, obj);
            else {
                binTreeNode<T> n;
                n = new binTreeNode(obj, NULL, NULL);
                node->left = n;
            }
    } else {
        if(node->right != NULL)
            insert(node->right, obj);
        else {

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM