首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >纯虚函数

纯虚函数
EN

Stack Overflow用户
提问于 2017-08-17 20:28:54
回答 2查看 121关注 0票数 0

嗨,Stack Hi用户!

需要一些纯粹的虚拟函数的帮助。我搜索了我得到的错误:“未定义的对'vtable for Sphere‘’的引用”,并在堆栈溢出处读取其他帖子。据我所知,链接器不知道功能的主体在哪里.

完整错误消息: /tmp/ccXEIJAQ.o:main.cpp(.rdata$.refptr._ZTV6Sphere.refptr._ZTV6Sphere+0x0):undefined引用‘’collect2:错误: ld返回1个退出状态

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

在Windows 7专业环境下在Cygwin 64位环境下进行编译。

抽象基类:原始子类:球面

下面是原始文件.h

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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 (为了清晰起见不需要省略的部分)。

代码语言:javascript
复制
#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的包含时,程序会编译。

任何帮助都是非常感谢的。我会继续搜索谷歌,看看我是否找到了解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-17 20:33:36

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

代码语言:javascript
复制
bool Sphere::intersection(double &intersect, const Vector3D &ray)

而不是

代码语言:javascript
复制
bool intersection(double &intersect, const Vector3D &ray)
票数 3
EN

Stack Overflow用户

发布于 2017-08-17 20:33:40

您忘了在函数定义中包括类名:

代码语言:javascript
复制
bool Sphere::intersection(double &intersect, const Vector3D &ray)
{
    //just trying to get it to compile.

    cout << "Hello.\n";
    return true;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45744443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档