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

Unable to call virtual methods inherited through two classes

本文关键字:两个 继承 方法 虚拟 调用      更新时间:2023-10-16

我试图创建一个从另一个类继承的类,而另一个类又继承自另一个只有纯虚方法的抽象类:

// 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

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

// 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编译

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

 Object::~Object()
 {
 }

 Vehicle::~Vehicle()
 {
 }

参考 class.ctor/1.2

类名不能是类型定义名。在构造函数中 声明,可选 decl-specifier-seq 中的每个 decl-说明符 应为好友、内联、显式或 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()'