c++ - 返回模板化结构对象指针时遇到问题

标签 c++ templates pointers

我正在类中编写所有方法原型(prototype),它们的定义将在类之外。这是我的 AVL 类设置:

template <class type>
class avlTree : public binarySearchTree<type>
{
public:
    avlTree();      //default constructor
    ~avlTree();     //destructor
    const type & findMin() const;
    const type & findMax() const;
    bool isEmpty() const;
    void printTree() const;
    void makeEmpty();
    void insert(const type & newData);
    void remove(const type & deleteItem);

private:
    template<class type>
    struct avlNode
    {
        type info;
        avlNode *left;
        avlNode *right;
        int height;

        avlNode(const type & data, avlNode *ll, avlNode *rl, int h = 0)
            : info{ data }, left{ ll }, right{ rl }, height{ h } {}
    };

    avlNode<type> * root;

    void insert(const type & newData, avlNode<type> * & p);
    void remove(const type & deleteItem, avlNode<type> * & p);
    avlNode<type>* findMin(avlNode<type> * p);  //these two methods are where I'm having problems.
    avlNode<type>* findMax(avlNode<type> * p);

};

我在编写内部(私有(private))findMin()时遇到问题和findMax()定义。为了清楚起见,不是实际的算法,而是返回 avlNode 对象指针的语法。类中的原型(prototype)没有显示错误,但是当我尝试在类之外编写其定义时,智能感知将不会显示,并且当我尝试编码 p->member 时,本地 p 指针不会显示其成员。 。通常,Intellsense 显示下拉菜单及其成员,但它没有显示。所以我知道存在某种语法错误。我认为这可能与模板的设置方式有关,但我不确定。那么我做错了什么?

我的方法定义遇到问题:

template <class type>
typename avlTree<type>::avlNode* avlTree<type>::findMin(avlNode * p)
{
    if (p == nullptr)
        return nullptr;
    if (p->left == nullptr)  //when I hover over 'p->left' that's when Intellisense says '<unknown> avlTree<type>::avlNode::left'
        return p;
    return findMin(p->left);  //same thing here
}

最佳答案

这应该可以做到:

template <typename type>
avlTree<type>::avlNode<type>* 
    avlTree<type>::findMin(avlNode<type>* p) {
  // ...
}

如果您还没有意识到这一点,则无需创建 avlNode本身就是一个模板。您正在启用不必要的灵活性,从而 avlTree<int>::avlNode<long>是一件事,但从未真正利用过所说的灵活性。制作avlNode一个普通的非模板成员类 - 这将大大简化问题。

关于c++ - 返回模板化结构对象指针时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129120/

相关文章:

c# - 为运行时初始化传递一个通用(模板)类

检查 ISBN 以查看其在 C 语言中是否有效

c - 参数在传递到函数时被破坏?

c++ - GDB 找不到行号,objdump 找到了

C++ 函数指针转换

email - 为什么 Magento 没有为交易电子邮件订单提取我的主题模板文件?

c++11 获取第一个(第二个等...)参数的类型,类似于 result_of

android - ConvexHull Android ndk 和 Opencv 中的参数无效

c++ - 如何检测我是否正在为 C++ 中的 64 位架构进行编译

c++ - 将 void 指针传递给具有 const char * const 的函数