c ++模板和继承

Arm*_*lak 1 c++ inheritance refactoring templates data-structures

我在使用模板和继承将代码分解为可重用部分时遇到了一些问题.我想实现我的树类和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
Run Code Online (Sandbox Code Playgroud)

tree.h中

#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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
...
Run Code Online (Sandbox Code Playgroud)

And*_*nck 8

双方tree.hnode.h尝试包括对方,包括守卫会阻止他们的一个看不到其他.

而不是#include "tree.h"尝试声明树像:

template <class T>
class tree;
Run Code Online (Sandbox Code Playgroud)

node.h

编辑:作为SBI的评论所说,它更有意义转发声明treenode.h比周围的其他方法,因为它是关于授予tree访问node通过一个friend宣言.