删除指向不完整类型"点"的指针;未调用析构函数

Deletion of pointer to incomplete type 'Point'; no destructor called

本文关键字:指针 析构函数 调用 删除 类型      更新时间:2023-10-16

我有两个文件:

Point.h:

class Point {
    int x;
    int y;
    char* name;
   public:
     Point() { name = new char[5]; }
    ~Point() { delete[] name; }
};

和:Line.h:

class Point;
class Line {
    Point* p;
  public:
    Line() {
      p = new Point[2];
      ....
      ...
    }
    ~Line() {
       delete[] p;
    }
};

但是当我编译时,我得到了下一个错误:

deletion of pointer to incomplete type 'Point'; no destructor called

感谢任何帮助!

您需要将#include "Point.h"添加到文件Line.h中。只能构造和删除完整的类型。

或者,从Line.h中删除成员函数定义,并将它们放在单独的文件Line.cpp中,并在文件中包含Point.hLine.h。这是一种典型的依赖性减少技术,它使代码的编译速度更快,尽管可能会失去某些内联机会。

您有前向声明的Point,这对于声明指针或引用很好,但对于编译器需要知道前向声明类的定义的其他任何事情都不好。

如果你需要头文件中的forward声明(你需要吗?)如果没有,就在Line.h中的#include "Point.h"),然后在#include中的Point.h的实现文件中实现Line函数。

扩展一下别人的建议——一条线总是由两个端点定义的。将这些点定义为堆分配内存没有多大意义。为什么不让这两点成为Line类的常规成员呢?这将节省内存,提高性能,并导致一个更干净的代码。但是,您必须包含"Point.h"才能正常工作。

使用名称空间向前声明示例。

// my header.h
namespace Poco {
    class TextConverter;
}