纯虚函数

时间:2017-08-17 20:28:55

标签: c++ linker

Hi Stack Over Flow用户!

需要一些纯虚函数的帮助。我用谷歌搜索了我得到的错误:" 对于Sphere' "的未定义的引用?并在堆栈溢出处阅读其他帖子。我收集的是链接器不知道函数体的位置......

完整的错误消息:/tmp/ccXEIJAQ.o:main.cpp(.rdata$.refptr._ZTV6Sphere[.refptr._ZTV6Sphere]+xx0)::????????????????????????????????????????????????????????????? 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;
}

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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

而不是

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

答案 1 :(得分:2)

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

bool Sphere::intersection(double &intersect, const Vector3D &ray)
{
    //just trying to get it to compile.

    cout << "Hello.\n";
    return true;
}