纯虚拟函数

Pure Virtual Functions

本文关键字:函数 虚拟      更新时间:2023-10-16

嗨,流用户堆栈!

需要一些纯虚拟函数的帮助。 我已经用谷歌搜索了我得到的错误:">对'vtable for Sphere'的未定义引用",并在堆栈溢出上阅读了其他帖子。 我收集到的是链接器不知道函数的主体在哪里......

完整的错误消息:/tmp/ccXEIJAQ.o:main.cpp(.rdata$.refptr._ZTV6Sphere[.refptr._ZTV6Sphere]+0x0(:对"vtable for Sphere"的未定义引用 collect2:错误:ld 返回 1 个退出状态

在粘贴以下相关代码部分之前:

在Windows 7 Professional下的Cygwin 64位环境中编译。

抽象基类:基元 子类:球体

以下是来自文件Primitive.h

#include "Color.h"
#include "Vector3D.h"
#ifndef PRIMITIVE_H
#define PRIMITIVE_H
class Primitive
{
public:
Primitive();
virtual ~Primitive();
virtual bool intersection(double &, const Vector3D &) = 0;    // pure virutal function
// other functions and private variables omitted for clarity.
};
#include "Primitive.cpp"
#endif

以下是来自Sphere.h

#include "Primitive.h"
#include "Point3D.h"
#include <iostream>
#include "Vector3D.h"
using namespace std; 
#ifndef SPHERE_H
#define SPHERE_H
class Sphere : public Primitive
{
public:
Sphere(const Point3D &, double, const Color &, double, const Color &, double, double);
Sphere(const Point3D &, double, const Color &, double, const Color &, double, double, const Color &, double, double);
bool intersection(double &, const Vector3D &);
Point3D getCenter();
double getRadius();
~Sphere();
friend ostream & operator << (ostream &, const Sphere &);
protected:
Point3D *center;
double radius;
};
#include "Sphere.cpp"
#endif

以下是来自Sphere.cpp(为清楚起见,部分不必省略...

#include <iostream>
#include "Point3D.h"
#include "Primitive.h"
#include "Sphere.h"
#include "Color.h"
#include "Vector3D.h"
using namespace std;
bool intersection(double &intersect, const Vector3D &ray)
{
//just trying to get it to compile.
cout << "Hello.n";
return true;
}

我已经覆盖了纯虚函数。 我什至尝试通过在 Sphere.h 的声明中添加">虚拟"关键字进行编译,但我得到了同样的错误。

代码中还没有球体对象的实例。 当我包含 Sphere.h 并尝试编译时,出现上述错误。 当我注释掉 Sphere.h 的包含时,程序会编译。

任何帮助将不胜感激。 我会继续搜索谷歌,看看我是否遇到解决方案。

问题是,在Sphere.cpp中,您正在定义另一个名为intersection的函数。你需要做的是实现在类中声明的函数,如下所示:

bool Sphere::intersection(double &intersect, const Vector3D &ray)

而不是

bool intersection(double &intersect, const Vector3D &ray)

您忘记在函数定义中包含类名:

bool Sphere::intersection(double &intersect, const Vector3D &ray)
{
//just trying to get it to compile.
cout << "Hello.n";
return true;
}