1

我正在编写一个函数来复制模板化二叉树。到目前为止,我有这个:

template <typename Item, typename Key>
Node* BSTree<Item,Key>::copy(Node* root) {
    if(root == NULL) return NULL;

    Node* left;
    Node* right;
    Node* to_return;

    left = copy(root->left());
    right = copy(root->right());

    to_return = new Node(root->data());
    to_return->left() = left;
    to_return->right() = right;

    return to_return;
}

但是当我尝试编译程序时,我遇到了多个错误,我无法弄清楚如何解决。它们都出现在模板声明之后的那一行。

1)错误C2143:语法错误:缺少';' 前'*'

2) 错误 C4430:缺少类型说明符 - 假定为 int

3) 错误 C2065:“项目”:未声明的标识符

4) 错误 C2065: 'Key' : 未声明的标识符

我在程序中的所有其他函数都可以正确编译并且模板没有问题,所以我不太确定为什么会这样。它已经在头文件中声明,并且肯定分配了一个返回类型,所以我很难过。

4

1 回答 1

2

Node的子类BSTree吗?如果是这样,则它不在返回类型的范围内,因此您必须对其进行限定:

template <typename Item, typename Key>
typename BSTree<Item,Key>::Node* BSTree<Item,Key>::copy(Node* root)

如果您有 C++11,那么auto也可以:

template <typename Item, typename Key>
auto BSTree<Item,Key>::copy(Node* root) -> Node
于 2012-12-05T03:33:49.353 回答