我刚开始学习 C++ 和 QT,抱歉,如果这是一个奇怪的问题。
我从两个类继承一个类,每个类都有一个构造函数。如何正确地将参数传递给这两个构造函数?
我有头等舱 - WirelessSensor
class WirelessSensor : public BoxSensor
{
public:
explicit WirelessSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr);
};
第二类 - SwitchSensor
class SwitchSensor : public BinarySensor
{
public:
explicit SwitchSensor(const unsigned int id, const QString &type, const bool &inverted, QObject *parent = nullptr);
};
这是我继承的类 - WirelessSwitchSensor.h
class WirelessSwitchSensor : public WirelessSensor, public SwitchSensor
{
public:
explicit WirelessSwitchSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent = nullptr);
};
但在 WirelessSwitchSensor.cpp 文件中它突出显示了错误:[/image/HQswI.png]
In constructor 'WirelessSwitchSensor::WirelessSwitchSensor(unsigned int, const QString&, const QString&, QObject*)': ..\Test\Sensor\wirelessswitchsensor.cpp:4:47: error: no matching function for call to 'SwitchSensor::SwitchSensor()' : WirelessSensor(id, type, address, parent)
无线开关传感器.cpp
WirelessSwitchSensor::WirelessSwitchSensor(const unsigned int id, const QString &type, const QString &address, QObject *parent)
: WirelessSensor(id, type, address, parent)
{
}
为我继承的类编写构造函数的正确方法是什么?
最佳答案
它真的很简单 - 您需要通过链接派生类中的初始化来直接调用它:
struct A
{
A(int a) { AA=a; }
int AA;
};
struct B
{
B(std::string b) { BB=b;}
std::string BB;
};
struct C : public A, public B
{
C(int a, std::string b)
:A(a),
B(b)
{
}
};
自己试试吧:)
关于c++ - 在具有多重继承的类构造函数中传递什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73618718/