[英]c++ templates and inheritance
我在使用模板和继承将代码分解为可重用部分时遇到一些问题。 我想实现我的树类和avltree类使用相同的节点类,并且avltree类从树类继承一些方法并添加一些特定的方法。 所以我想出了下面的代码。 编译器在tree.h中抛出错误,如下所示,我真的不知道该如何克服。 任何帮助表示赞赏! :)
node.h:
#ifndef NODE_H
#define NODE_H
#include "tree.h"
template <class T>
class node
{
T data;
...
node()
...
friend class tree<T>;
};
#endif
树
#ifndef DREVO_H
#define DREVO_H
#include "node.h"
template <class T>
class tree
{
public: //signatures
tree();
...
void insert(const T&);
private:
node<T> *root; //missing type specifier - int assumed. Note: C++ does not support default-int
};
//implementations
#endif
avl.h
#ifndef AVL_H
#define AVL_H
#include "tree.h"
#include "node.h"
template <class T>
class avl: public tree<T>
{
public: //specific
int findMin() const;
...
protected:
void rotateLeft(node<T> *)const;
private:
node<T> *root;
};
#endif
avl.cpp(我尝试将标头与实现分开,在我开始将avl代码与树代码合并之前,它就起作用了)
#include "drevo"
#include "avl.h"
#include "vozlisce.h"
template class avl<int>; //I know that only avl with int can be used like this, but currently this is doesn't matter :)
//implementations
...
tree.h
和node.h
尝试互相包含,include防护将阻止其中一个看到对方。
代替#include "tree.h"
尝试像下面这样声明树:
template <class T>
class tree;
在node.h
编辑:正如sbi在评论中建议的那样,在node.h
转发声明tree
比在其他方法中更有意义,因为这是关于通过friend
声明授予对node
tree
访问权限。
不要在“ node.h”中#include“ tree.h”。
另外,您已经在tree
和avl
类中声明了root
。 将tree::root
限定为protected
并删除avl::root
。
您的问题是tree.h包含node.h,反之亦然。 我不会认为节点必须了解树或授予它友谊是必要的(或很有意义),因此我将其删除。
问题是由于tree.h和node.h之间头文件的循环依赖关系。 由于node.h包含tree.h,因此在编译树类时,编译器不知道节点的类型是什么。 由于您仅将其用于声明朋友,因此无需在node.h中包含头文件tree.h
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.