无法调用通过两个类继承的虚方法

时间:2018-04-05 22:51:26

标签: c++

我试图创建一个继承自另一个类的类,该类继承自另一个只使用纯虚方法的抽象类:

// objects.cpp:

class Object
{
public:
    virtual void generate() = 0;
    virtual ~Object() = 0;
};

class Vehicle: public Object
{
    virtual void generate() = 0;
protected:
  // Attributes inherited by Bike objects.
public:
    virtual ~Vehicle() = 0;

};

class Bike: public Vehicle
{
private:
  // Attributes specific to Bike class objects.
public:
    void generate()
    {
      // Takes the data from the object being called on and writes them to a file.
    }
    Bike()
    {
      // Declaring a bike launches the constructor which randomly generates and assigns data.
    }
    ~Bike() {}

};
void trigger_generation(Object & opoint)
{
    opoint.generate();
}

这是头文件:

// objects.hpp

#ifndef OBJECTS_H
#define OBJECTS_H

class Object
{
public:
    virtual void generate();
    virtual ~Object();
};

class Vehicle: public Object
{
protected:
  // Attributes inherited by Bike objects.
public:
    virtual ~Vehicle();

};

class Bike: public Vehicle
{
private:
  // Attributes specific to Bike class objects.
public:
    void generate();
    Bike();
    ~Bike();
};

void trigger_generation(Object & opoint);

#endif // OBJECTS_H

然后,在main.cpp文件中,我在Bike类对象上运行generate()方法:

// main.cpp
#include "objects.hpp"

int main(int argc, char *argv[])
{

    Bike itsactuallyabicycle;
    trigger_generation(itsactuallyabicycle);

}

我最终得到了这些错误:
main.cpp:(.text+0x27): undefined reference to `Bike::Bike()'
main.cpp:(.text+0x3f): undefined reference to `Bike::~Bike()'
main.cpp:(.text+0x64): undefined reference to `Bike::~Bike()'

导致这些错误的原因是什么?如何绕过它们以便可以正常调用Bike类方法?

编辑:使用g++ main.cpp objects.hpp objects.cpp

进行编译

2 个答案:

答案 0 :(得分:1)

纯虚拟析构函数在C ++中是合法的,但它必须有一个正文。

 Object::~Object()
 {

 }

 Vehicle::~Vehicle()
 {

 }

答案 1 :(得分:0)

参考class.ctor/1.2

  

类名不应是typedef-name。在构造函数中   声明,可选的decl-specifier-seq中的每个decl-specifier   应该是朋友,内联,明确或constexpr。   [实施例:

struct S {
   S();      // declares the constructor
};

S::S() { }   // defines the constructor
     

- 结束示例]

Bike itsactuallyabicycle;

将调用hpp文件中的声明:

Bike();
~Bike();

因此,Bike();~Bike();只是声明,而不是定义导致:

undefined reference to `Bike::Bike()'
undefined reference to `Bike::~Bike()'