【问题标题】:N-tree, shared_ptr and "cannot declare field "tnode::data" to be of abstract type FigureN-tree、shared_ptr 和“不能将字段“tnode::data”声明为抽象类型图
【发布时间】:2015-10-21 09:42:36
【问题描述】:

我最近开始学习面向对象编程,现在我面临着用shared_ptr 指向程序的常用指针更改程序的问题。 我尝试使用容器(n-tree)创建一个程序,其中包含两种类型的图形:六边形和菱形。而且我还必须使用shared_ptr。 第一个问题是: 例如,我有一个函数,它向 n-tree 添加一个元素:

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 会怎样? 第二个问题是编译器没有看到 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(){}
};

六边形.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;
};

菱形.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 Figure)中,编译器还写 “不能将字段图声明为抽象类型图”

最后一个问题。据我了解,在 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();
};

那么,你能说我,我错在哪里以及如何解决问题。

【问题讨论】:

  • 指针的大量使用不像看起来像 C++ 或 OOP。
  • 您是否有理由不使用 C++ newdelete 运算符?因为如果你使用 mallocfree 构造函数和析构函数实际上不会被调用,这可能会导致不好的事情。
  • @JoachimPileborg 在“添加”中是正确的:std::shared_ptr&lt;tnode&gt;p = new tnode;?

标签: c++ shared-ptr weak-ptr


【解决方案1】:

tnode 结构中,您声明了Figure 类的实例,因为它是抽象的,所以不能这样做。您需要改用指针。

add 函数相同,您通过值传递 Figure 实例,因为它是抽象的,所以无法完成。

【讨论】:

  • 我需要在函数中到处使用Figure *figure 吗?在Figure *data的结构中?
  • @MichaelPister 是的,你永远不能拥有一个抽象类的实例,其中包括诸如按值传递之类的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 2013-11-15
  • 1970-01-01
  • 2021-12-07
  • 2015-09-11
  • 2021-06-10
相关资源
最近更新 更多