【问题标题】:Unexpected errors that I can't seem to fix我似乎无法修复的意外错误
【发布时间】:2012-12-05 03:24:38
【问题描述】:

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

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:“密钥”:未声明的标识符

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

【问题讨论】:

    标签: c++ templates compiler-errors binary-tree


    【解决方案1】:

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

    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
    

    【讨论】:

    • 非常感谢!这正是问题所在!
    • @BrandonBosso 刚刚意识到参数在范围内,所以我更新了代码以防你错过它。
    猜你喜欢
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多