gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:47 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com