C++为什么我需要在扩展类中指定函数的作用域

C++ Why do I need to specify the scope of a function in an extended class?

本文关键字:函数 作用域 扩展 为什么 C++      更新时间:2023-10-16

类:

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。

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

对于非模板类来说,这是正确的,因为这样的查找是唯一定义的。在这种情况下,您使用的是模板类,因此AvlTree的查找不会唯一定义类型。事实上,AvlTree本身甚至不是一个类型,而是描述了一组可以使用不同模板参数创建的类型。

基类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);