gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:17 25 4
gpt4 key购买 nike

我有一个名为 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.

关于c++ - 创建一个具有两个可能继承的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50309403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com