c++ - 基类有不完整的类型

标签 c++ inheritance

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

这是我的类(class)要点:

#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 header 中),所以我定义了 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.

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

我正在用 clang 编译。

最佳答案

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

class Point3D;

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

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

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

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

我相信您能弄清楚如何将它拆分到头文件和源文件中。 (例如,前两部分可以放在 Point.hpp 中,第三部分可以放在 Point3D.hpp 中,其中包括 Point.hpp,然后最终实现可以放在 Point.cpp 中,其中包括 Point.hppPoint3D.hpp。)

关于c++ - 基类有不完整的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594549/

相关文章:

C++ std::atomic - 不可能基于共享原子变量同步 2 个线程

c++ - 来自 VCGlib 的示例代码使 Visual Studio 2013 崩溃

c++ - 如何为具有私有(private)对象作为属性的类编写移动构造函数和赋值运算符?

c++ - 在类公共(public)方法中创建一个新结构

c++ - 转换错误,std::string -> LPCSTR

c++ - stringstream 问题 - vector 迭代器不可取消引用

c++ - VC++ 警告 C4356 : static data member cannot be initialized via derived class

c# - 为什么 AcquireRequestState 隐藏 Inherited HttpApplication.AcquireRequestState 而 Application_Start 则不隐藏?

c# - 我如何使用 NUnit 创建一个通用的 BaseTest,我可以从它继承并从 base 运行测试?

javascript - 通过 setter 设置继承的属性