创建一个具有两个可能继承的类

creating a class with two possible inheritances

本文关键字:继承 两个 一个 创建      更新时间:2023-10-16

我有一个名为 Radio 的类,我希望能够从名为 Serial 的类或名为 Stream 的类继承,具体取决于对象的创建方式。我认为这可以使用以下模板来完成:

template<class InterfaceType>
class Radio : public InterfaceType
{
...
};

并创建类似

Radio<Serial> serialRadio;
Radio<Stream> streamRadio;

这是个好主意吗?

在我定义类中函数的实现文件中,我收到如下错误:

radio.cpp:52:6: error: ‘template<class InterfaceType> class Radio’ used without template parameters
void Radio::mavlinkReceiveByte(uint8_t data) {
^~~~~

这是我对你想要什么的猜测:

测试(也在 godbolt.org(

#include <iostream>
#include <string>
// -- Data source --
class Stream {
public:
explicit Stream(int x) {}
std::string get_data() { return "tweet."; }
};
class Serial {
public:
std::string get_data() { return "chirp."; }
};
// -- Interfaces --
template<class Data_source>
class Radio {
public:
explicit Radio(Data_source&& ds) : data_source(std::move(ds)) {}
void nom();
private:
Data_source data_source;
};
template <class D>
void Radio<D>::nom() {
std::cout << data_source.get_data() << "n";
}
template<class Data_source>
class Radio_alarm : Radio<Data_source> {
using Base = Radio<Data_source>;
public:
explicit Radio_alarm(Data_source&& ds)
: Base(std::move(ds)) {}
void nom_x10() {
for (int i = 0; i < 10; ++i) {
std::cout << "[" << i << "]: ";
Base::nom();
}
}
};
// -- Test --
int main() {
Radio stream_r(Stream(1));
Radio serial_r((Serial()));
serial_r.nom();
Radio_alarm r_alarm((Stream(1)));
r_alarm.nom_x10();
}

结果:

chirp.
[0]: tweet.
[1]: tweet.
[2]: tweet.
[3]: tweet.
[4]: tweet.
[5]: tweet.
[6]: tweet.
[7]: tweet.
[8]: tweet.
[9]: tweet.

在头文件中找出我需要的语法:

template<class InterfaceType>
class Radio : public InterfaceType
{
public:
struct buffer
{
uint16_t len;
std::shared_ptr<uint8_t[]> buf;
};
struct channels {
uint16_t rollPWM, pitchPWM, yawPWM, throttlePWM;
};
buffer sendHeartbeat(uint8_t mode, uint8_t status);
void mavlinkReceiveByte(uint8_t data);
void mavlinkReceivePacket(uint8_t *packet);
channels getRCChannels();
private:
channels pwmInputs;
};

实现文件中的示例函数:

template<typename InterfaceType>
typename Radio<InterfaceType>::buffer Radio<InterfaceType>::sendHeartbeat(uint8_t mode, uint8_t status) {
mavlink_message_t msg;
uint16_t len;
uint8_t buf[MAVLINK_MAX_PACKET_LEN];
mavlink_msg_heartbeat_pack(SYSID, COMPID, &msg, MAV_TYPE_QUADROTOR, MAV_AUTOPILOT_GENERIC, mode, 0, status);
len = mavlink_msg_to_send_buffer(buf, &msg);
buffer sendBuffer;
sendBuffer.buf = (std::shared_ptr<uint8_t[]>)buf;
sendBuffer.len = len;
return sendBuffer;
}

实现函数中的类型很讨厌,但它编译...如果有人建议让它看起来更好,那将是有帮助的。