无法调用通过两个类继承的虚拟方法
Unable to call virtual methods inherited through two classes
我试图创建一个从另一个类继承的类,而另一个类又继承自另一个只有纯虚方法的抽象类:
// 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()'
相关文章:
- 两个继承类如何调用彼此的方法?
- 从两个不同类继承的非虚拟基类的访问成员
- 创建一个具有两个可能继承的类
- 无法调用通过两个类继承的虚拟方法
- 从两个类继承的空类,一个是模板
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 从同一类的两个不同模板副本继承时重载
- 从两个无法改变的标头继承
- 从 C++ 中的两个类继承并插入到列表中
- 通过调用两个参数化的父类构造函数来构造继承的类
- 继承-在两个不同的类中使用相同的方法名
- 两个不同的继承指针地址是如何相等的
- 具有不同签名的两个函数的继承隐藏了非虚函数
- 从两个抽象类继承
- 基于可变参数模板的两个交互类的多重继承
- 从两个类继承的类,具有相同的函数原型,彼此冲突
- 从两个模板参数多重继承的奇怪之处
- 防止一个类的派生类对两个类进行多重继承
- 当继承基模板类并将两个类文件放在单独的头文件中时,为什么会出现重定义错误
- 如何在编译时推导出两个类型共有的继承树的根(如果存在)