我正在类中编写所有方法原型(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/