0

我有一个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

在我的课堂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

但是,这是行不通的。当我编译它时,它给了我以下错误:

./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.

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

我正在用clang编译。

4

1 回答 1

8

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

class Point3D;

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

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

Point3D Point::add(const Point &)
{
    // implementation
}

函数返回类型可能不完整,这就是您的类定义Point这样工作的原因。

我相信您可以弄清楚如何将其拆分为头文件和源文件。(比如前两部分可以进入Point.hpp,第三部分可以进入Point3D.hppincludes Point.hpp,最后的实现可以进入Point.cppincludesPoint.hppPoint3D.hpp.)

于 2012-11-27T22:52:47.783 回答