【问题标题】:Nested Class Causing Problems with Templating嵌套类导致模板问题
【发布时间】:2012-05-04 15:55:27
【问题描述】:

对于我的数据结构类,我们被要求采用以前实现的平衡树(来自之前的项目)并使用它来实现 C++ 标准映射类的部分内容。

http://cplusplus.com/reference/stl/map/

我认为最明显的第一步是对整个类进行模板化,允许单独的键和存储类型。当然,我遇到了模板问题。通常,我的模板一直有效,直到我尝试对使用本地嵌套数据类型“rbNode”的函数进行模板化。如果我在函数定义中包含模板参数,则会出现语法错误。如果我将它们排除在外,我会收到“不包括模板参数”错误。

这是在 Visual Studio 2010 中给我错误的类实现(下面列出的错误):

#include <cstdlib>
#include <iostream>
template <class key_type, class T>
class myMap
{
private:
    //typedef pair<const key_type, T> value_type;
    struct rbNode
    {
        //value_type ref;
        int element;
        rbNode * left;
        rbNode * right;
        bool red;
        rbNode(int key)
        {
            left = NULL;
            right = NULL;
            //ref.first = key;
            //ref.second = element;
            element = key;
            red = true;
        }
    };
    rbNode * root;
    bool search(int , rbNode *);
    rbNode * LL_Rotation(rbNode *);
};

template <class key_type, class T>
myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr) // errors occur on this line
{
    rbNode * temp = curr->right;
    curr->right = temp->left;
    temp->left = curr;

    curr->red = 1;
    temp->red = 0;

    return temp;
}

然而,这个函数编译得很好,上面的函数被注释掉了:

template <class key_type,class T> 
bool myMap<key_type,T>::search(int key,rbNode * tree)
{
    if(tree!=NULL)
        if(tree->element==key)
            return true;
        else
            if(key< tree->element)
                return search(key,tree->left);
            else
                return search(key,tree->right);
    else
        return false;
}

特别是,我得到了

missing ';' before '*' missing type specifier - int assumed. Note: C++ does not support default-int 在行中,“LLRotation”名称的实现在(在评论中指出)。我对模板不是很有经验,所以我觉得我犯了一个非常愚蠢的错误。无论如何,如果您需要更多我的代码或更多信息,请告诉我。任何帮助是极大的赞赏。

注意:我确信我的代码中有很多不好的做法,等等。我还在学习。随意指出它们,但我最关心的是模板问题。

【问题讨论】:

  • 如果你能发布一个最小可编译的例子会很有帮助
  • 对不起。我已经修改了帖子。第一个块应该是可编译的。

标签: class templates map nested red-black-tree


【解决方案1】:

您只是缺少一个 typename 用于从属名称:

template <class key_type, class T>
typename myMap<key_type,T>::rbNode* myMap<key_type,T>::LL_Rotation(rbNode * curr)
^^^^^^^^

【讨论】:

  • 就是这样!非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多