Deletion of pointer to incomplete type 'Point&

2019-06-17 03:16发布

I have 2 files:

Point.h:

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

and: Line.h:

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

but when I compile, I got the next error:

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

any help appreciated!

3条回答
看我几分像从前
2楼-- · 2019-06-17 03:40

To expand a bit on a suggestion other people gave -- a line is always defined by two end points. There isn't much point in defining these points as a heap-allocated memory. Why not make the two points regular members of the Line class? This will save memory, improve performace and lead to a cleaner code as well. You'll have to include "Point.h" for this to work, though.

查看更多
唯我独甜
3楼-- · 2019-06-17 03:45

You have forward declared Point, which is fine for declaring a pointer or reference, but not fine for anything else in which the compiler would need to know the definition of the forward declared class.

If you need the forward declaration in the header file (do you? If not, just #include "Point.h" in Line.h ) then implement your Line functions in an implementation file which #includes Point.h.

查看更多
在下西门庆
4楼-- · 2019-06-17 03:50

You need to add #include "Point.h" into your file Line.h. You can only construct and delete complete types.

Alterntively, remove the member function definitions from Line.h, and put them in a separate file Line.cpp, and include Point.h and Line.h in that file. This is a typical dependency reduction technique which makes code faster to compile, although at a potential loss of certain inlining opportunities.

查看更多
登录 后发表回答