基类具有不完整的类型

Ant*_*neG 0 c++ inheritance

我有一个Point我继承的基类Point3D.但是,由于某种原因,类Point必须始终返回Point3D操作add,因此我将其包含在我的包含中.

这是我的班级Point:

#ifndef POINT_H
#define POINT_H

#include "Point3D.hpp"

class Point{

  public:
    Point(double, double, double);

    void print() const;
    Point3D add( const Point& );

  protected:
    double mX;
    double mY;
    double mZ;

};

#endif
Run Code Online (Sandbox Code Playgroud)

在我的班上Point3D,我知道我还没有遇到过Point我第一次被调用的定义(因为Point3D它包含在Point标题中),所以我定义class Point;,然后我定义我将使用的部分Point:

#ifndef POINT3D_H
#define POINT3D_H

#include <iostream>
#include "Point.hpp"  // leads to the same error if ommitted

class Point;    

class Point3D : public Point {

  public:
        Point3D(double, double, double);
        void print() const ;
        Point3D add(const Point&);
};

#endif
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用.当我编译它时,它给我以下错误:

./tmp/Point3D.hpp:9:24: error: base class has incomplete type
class Point3D : public Point {
                ~~~~~~~^~~~~
./tmp/Point3D.hpp:7:7: note: forward declaration of 'Point'
class Point;
      ^
1 error generated.
Run Code Online (Sandbox Code Playgroud)

这里的问题是#include "Point.hpp"要从我的Point3D声明中删除包含.但是,这样做会导致相同的结果,我认为标题保护基本上会完成同样的事情.

我正在和clang编译.

Ker*_* SB 6

您不能从不完整的类型继承.您需要按如下方式构建代码:

class Point3D;

class Point
{
    // ...
    Point3D add(const Point &);
    // ...
};

class Point3D: public Point
{
    // ...
};

Point3D Point::add(const Point &)
{
    // implementation
}
Run Code Online (Sandbox Code Playgroud)

函数返回类型可能不完整,这就是为什么你的类定义是Point这样的.

我相信你可以弄清楚如何在头文件和源文件之间拆分它.(例如,前两个部分可以进入Point.hpp,第三个Point3D.hpp部分包括Point.hpp,最终实现可以进入Point.cpp包括Point.hppPoint3D.hpp.)