C ++为什么我需要在扩展类中指定函数的范围?

时间:2016-05-14 06:41:37

标签: c++

班级:

template <class TYPE, class KTYPE>
class ExtAvlTree : public AvlTree<TYPE, KTYPE> {
    public:
        void ExtAvlTree_PrintDictionary();
        void ExtAvlTree_ProcessNode (KTYPE key);
        void ExtAvlTree_insertNewWord(string, int);
};

当我想在AvlTree中使用一个函数时,我必须这样做:

template <class TYPE, class KTYPE>
void ExtAvlTree<TYPE, KTYPE>::ExtAvlTree_insertNewWord(string word, int data) {
    TreeNode newWord;
    newWord.key = word;
    newWord.data = data;
    AvlTree<TYPE, KTYPE>::AVL_Insert(newWord); //look here <--
}

如果我没有指定范围“AvlTree ::”,我会收到错误:

error: there are no arguments to 'AVL_Insert' that depend on a template parameter, so a declaration of 'AVL_Insert' must be available [-fpermissive]|

据我所知,在派生类中使用基类中的函数时,我不必指定范围。如果重要,我使用的是代码块16.01 IDE。

2 个答案:

答案 0 :(得分:1)

  

据我所知,在派生类中使用基类中的函数时,我不必指定范围。

非模板化类是正确的,因为这种查找是唯一定义的。在这种情况下,您使用模板化类,因此AvlTree的查找不能唯一地定义类型。实际上,AvlTree本身甚至不是一种类型,但描述了一组可以使用不同模板参数创建的类型。

答案 1 :(得分:0)

基类AvlTree不是非依赖基类,AVL_Insert是非依赖名称。不依赖的基类中不会查找非依赖名称。

要更正此代码,您需要使名称AVL_Insert相互依赖,因为只能在实例化时查找相关名称。那时,必须探索必须探索的确切基础专业化。

如你所示,你可以

AvlTree<TYPE, KTYPE>::AVL_Insert(newWord);

或使用this

this->AVL_Insert(newWord);

或使用using

using AvlTree<TYPE, KTYPE>::AVL_Insert;
AVL_Insert(newWord);