C++多重继承,没有多重定义的时候?

标签 c++ multiple-inheritance virtual-inheritance multiple-definition-error

我正在为一个嵌入式 C/C++ 项目实现硬件驱动程序,并试图让事情在未来的项目中更加灵活。

我在 LCD.hpp/LCD.cpp 中完成了绝大部分工作,其中有一个类具有五个虚函数。其中四个用于调整 GPIO 引脚和发送 SPI 消息,第五个用于实现各种字体。一个简短的类声明如下:

//LCD.hpp
#include <cstdint>

#ifndef LCD_HPP
#define LCD_HPP
class LCD {
    public:
        virtual void write_character(char what) = 0; //Stores data into a buffer in LCD through another function
    protected:
        virtual void SPI_TX(uint8_t *TXData, uint8_t length, bool ToBeContinued) = 0;
        virtual void update_RST(bool pinstate) = 0;
        virtual void update_DC(bool pinstate) = 0;
        virtual void update_backlight(uint8_t brightness) = 0;
};
#endif

继续,我实现了一个字体打印 write_character。

//LCD_FixedWidth.hpp
#include <cstdint>
#include "LCD.hpp"

#ifndef LCD_FIXEDWIDTH_HPP
#define LCD_FIXEDWIDTH_HPP
class LCD_FixedWidth : virtual public LCD {
    public:
        void write_character(char what);
};
#endif

现在是各种硬件位的时候了。

//LCD_hardware.hpp
#include <cstdint>
#include "LCD.hpp"
#include "LCD_FixedWidth.hpp"

#ifndef LCD_HARDWARE_HPP
#define LCD_HARDWARE_HPP
class LCD_hardware : virtual public LCD {
    protected:
        void SPI_TX(uint8_t *TXData, uint8_t length, bool ToBeContinued);
        void update_RST(bool pinstate);
        void update_DC(bool pinstate);
        void update_backlight(uint8_t brightness);
};

然后是一个将它们联系在一起的类,仍在 LCD_hardware.hpp 中...

class LCD_meta : public LCD_hardware, public LCD_FixedWidth {
    public:
        void write_character(char what) { LCD_FixedWidth::write_character(what); };
    protected:
        void SPI_TX(uint8_t *TXData, uint8_t length, bool ToBeContinued) { LCD_hardware::SPI_TX(TXData, length, ToBeContinued); };
        void update_RST(bool pinstate) { LCD_hardware::update_RST(pinstate); };
        void update_DC(bool pinstate) { LCD_hardware::update_DC(pinstate); };
        void update_backlight(uint8_t brightness) { LCD_hardware::update_backlight(brightness); };
};
#endif

对于所有这些,我得到了 LCD_FixedWidth::write_character(char) 错误的多重定义。有人看到我在这里遗漏了什么吗?我所有的 header 都受到了适当的保护,我只能看到 write_character 的一种实现...

最佳答案

这是由于在同一个头文件中包含 LCD_meta 和 LCD_hardware 造成的。 LCD_hardware 函数的代码在一个实现文件中,因此 LCD_meta 类实际上还没有定义这些函数……每个文件一个类!

关于C++多重继承,没有多重定义的时候?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28650479/

相关文章:

c++ - 根据模板参数有条件地启用成员函数

c++ - 没有enable_shared_from_this 可以实现shared_from_this 吗?

c++ - 多重继承 : calling all the overriden functions

c++ - 为什么单一虚拟继承不足以解决可怕的菱形继承(钻石问题)?

c++ - 什么时候虚拟继承是一个好的设计?

c++ - 从 vector 的元素成员方法插入 vector 元素 destroys *this

c++ - 我怎样才能模一个大的整数值

C++ 类定义。属性作为指针?哪个是正确的方法?

oop - 处理游戏中的单一继承

c++ - 在派生类接口(interface)中隐藏基类的特定功能