簡體   English   中英

c ++模板和繼承

[英]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.hnode.h嘗試互相包含,include防護將阻止其中一個看到對方。

代替#include "tree.h"嘗試像下面這樣聲明樹:

template <class T>
class tree;

node.h

編輯:正如sbi在評論中建議的那樣,在node.h轉發聲明tree比在其他方法中更有意義,因為這是關於通過friend聲明授予對node tree訪問權限。

不要在“ node.h”中#include“ tree.h”。

另外,您已經在treeavl類中聲明了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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM