c++ - 在具有多重继承的类构造函数中传递什么?

标签 c++ qt multiple-inheritance

我刚开始学习 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/

相关文章:

c++ - 带有 ACK : Search for all #pragma not ending in once 的 Vim

c++ - 是否可以使用函数在 C++ 中重新创建 for 循环

c++ - 尝试在不了解某些内容的情况下编译 .h 文件

c++ - 用户模板化定义结构的 QList

c++ - 命令提示符关闭而不接受输入

qt - 强制 QWebEngine 使用软件渲染

c++ - 在第二个屏幕上显示对话框/框架全屏唱 QT/c++

C++ 接口(interface)的公共(public)虚拟继承与实现的私有(private)继承

c++ - "Reparent"来自编译代码的类

java - 继承的选择