从外部定义的类继承时,使用不完整类型类错误无效

Invalid use of incomplete type class error when inheriting from class defined externally

本文关键字:用不完 类型 错误 无效 定义 继承 从外部      更新时间:2023-10-16

文件夹结构如下:

src/
├── drivers
│   ├── drv_rs485_bus.h
│   └── rs485_bus
│       ├── rs485_device.cpp
│       └── rs485_device.h
└── modules
    └── dx_servos
        ├── CMakeLists.txt
        ├── dx_servo.cpp
        └── dx_servo.h

rs485_device.h中是一个类:

#pragma once
#include <cstdint>
#include <memory>
#include "rs485_bus.h"
namespace rs485 {
class Rs485Device {
   public:
    explicit Rs485Device(std::shared_ptr<rs485::Rs485Bus> bus, uint8_t address);
    ~Rs485Device();
   private:
    std::shared_ptr<rs485::Rs485Bus> _bus;
    uint8_t _address;
};
}  // ns: rs485

drv_rs485_bus.h暴露了类Rs485Device,并且应该包含在应该使用该类的任何内容中。它有以下内容:

#pragma once
#include <cstdint>
#include <memory>
namespace rs485 {
class Rs485Bus;
class Rs485Device;
extern std::shared_ptr<Rs485Bus>
get_bus();
extern bool
get_open();
}

现在,我想创建一个类DxServo,它继承Rs485Device。我包括drv_rs485_bus.h,并像这样声明DxServo:

#pragma once
#include <drivers/drv_rs485_bus.h>
#include <cstdint>
#include <memory>
#include <string>
namespace dx_servo {
class DxServo : public rs485::Rs485Device {
   public:
    explicit DxServo(const std::string name, uint16_t address,
                     std::shared_ptr<rs485::Rs485Bus> bus);
    ~DxServo();
   private:
    uint16_t _address;
    std::shared_ptr<rs485::Rs485Bus> _bus;
};
}  // ns: dx_servo
现在,在编译时,我得到以下错误:
../src/modules/dx_servos/dx_servo.h:12:31: error: invalid use of incomplete type ‘class rs485::Rs485Device’
 class DxServo : public rs485::Rs485Device {
                               ^
compilation terminated due to -Wfatal-errors.

是什么原因导致的?

为了能够从一个类继承,您需要完整的定义,而不仅仅是一个前向声明。您需要包含rs485_device.h头文件。