2015-10-21 44 views
0

我最近開始學習面向對象的編程,現在我面臨着通常指向程序的指針改變程序的問題與shared_ptr 我嘗試創建一個容器(n-tree),其中包含twi類型的數字:六邊形和菱形程序,我還必須使用shared_ptr。 第一個問題是: 例如,我有一個功能,即添加一個元素到正樹:N-tree,shared_ptr和「無法聲明字段」tnode :: data「爲抽象類型圖

tnode *add(tnode **node, const Figure figure) { 
tnode *pnext = NULL; 
tnode *p = (tnode *)malloc(sizeof(tnode)); 
p->data = rhombus; 
p->parent = NULL; 
p->prev = NULL; 
p->next = NULL; 
p->child = NULL; 
if (*node == NULL) 
    *node = p; 
else if ((*node)->child == NULL) { 
    p->parent = *node; 
    (*node)->child = p; 
} else { 
    pnext = (*node)->child; 
    while (pnext->next != NULL) 
     pnext = pnext->next; 
    p->parent = *node; 
    p->prev = pnext; 
    pnext->next = p; 
} 
return p; 
} 

...或破壞樹:

void destroy(tnode **node) { 


if (*node == NULL) 
    return; 
if ((*node)->next != NULL) 
    destroy(&(*node)->next); 
if ((*node)->child != NULL) 
    destroy(&(*node)->child); 
free(*node); 
*node = NULL; 
} 

它將如何看待std :: shared_ptr? 以及第二個問題是,compilator沒有看到的是,圖是用於其他兩個數字一個父類:

Figure.h

class Figure { 
public: 
    virtual bool operator==(const Figure& right); 
    virtual &Figure::operator=(const Figure& right); 
    virtual double Square() = 0; 
    virtual void Print() = 0; 
    virtual ~Figure(){} 
}; 

Hexagon.h

#include "Figure.h" 

class Hexagon : public Figure{ 
public: 
Hexagon(); 
Hexagon(std::istream &is); 
Hexagon(float side); 
Hexagon(const Hexagon& orig); 

bool operator==(const Hexagon& right); 
Hexagon& operator=(const Hexagon& right); 

double Square() override; 
void Print() override; 

virtual ~Hexagon(); 
//private: 
int side; 
}; 

Rhombus.h

#include <cstdlib> 
#include <iostream> 
#include "Figure.h" 

class Rhombus : public Figure{ 
Rhombus(); 
Rhombus(std::istream &is); 
Rhombus(int side, float angle); 
Rhombus(const Rhombus& orig); 

bool operator==(const Rhombus& right); 
double Square();// override; 

Rhombus& operator=(const Rhombus& right); 

virtual ~Rhombus(); 
//private: 
int side; 
float angle; 
}; 

在函數「add」和「destroy」中(其中參數是A Figu )編譯器也寫道 「不能聲明字段圖是抽象類型的圖」

而最後一個問題。據我所知,在N-Tree的結構中,一部分結構「擁有」了一些其他結構,因此需要wear_ptr。有錯誤嗎?

struct tnode { 
Figure data; 
std::weak_ptr<tnode>parent; 
std::weak_ptr<tnode>prev; 
std::shared_ptr<tnode>next; 
std::shared_ptr<tnode>child; 
~tnode(); 
}; 

那麼,你可以說我,我錯了,如何解決問題。

+1

指針的這種大量使用不會看起來像C++或OOP。 – Downvoter

+0

有沒有原因你不使用C++'new'和'delete'運算符?因爲如果你使用'malloc'和'free',構造函數和析構函數將不會被調用,這可能會導致不好的結果。 –

+0

@JoachimPileborg就是在「添加」中的權利:'std :: shared_ptr p = new tnode;'? –

回答

0

tnode結構,你聲明Figure類,無法做到的,因爲它是抽象的實例。您需要改用指針。

add函數一樣,您通過一個值爲Figure的實例,因爲它是抽象的,所以無法完成。

+0

我需要在函數中使用'圖* figure'嗎? 而在一個結構'圖*數據'? –

+0

@MichaelPister是的,你永遠不可能有一個抽象類的實例,它包括諸如按值傳遞之類的東西。 –

相關問題