纯虚拟函数
Pure Virtual Functions
嗨,流用户堆栈!
需要一些纯虚拟函数的帮助。 我已经用谷歌搜索了我得到的错误:">对'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;
}
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 当覆盖存在时调用基本虚拟"binded to object"函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 是否可以使用函数指针调用虚拟析构函数?
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- 虚拟继承基构造函数消除
- "虚拟""覆盖"析构函数
- 类中的虚拟布尔函数参数不起作用
- 用纯虚拟函数兜圈子
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- 尝试在 QLabel 上绘画失败(无法在没有对象的情况下调用成员函数"虚拟无效 QLabel::p aintEvent(QPaintEvent*)")
- 声明析构函数虚拟就足够了吗?
- 视觉 C++当我们在基类中使函数成为纯虚拟时,那么在子类中再次使相同的函数虚拟的必要性是什么
- 重载函数(虚拟/非虚拟)