利用父对象初始化子对象的方法(理解继承和构造过程)

0 引出

在编写某CAN软件上位机程序时,打算采用CAN设备父类衍生通道子类,由通道子类实现多线程的思路。

通常一个CAN卡不止一个通道,因此需要继承CAN设备父类的一些成员,因此,需要用父类实例初始化子类实例。

1 实现方法

以下为实例代码:

  • 父类:
class TestInit : public QObject {
    Q_OBJECT
public:
    TestInit(QObject* parent = nullptr, int father_age = 0);
    void printFather() {
        std::cout << "Father age is " << father_age << std::endl;
    }
public:
    int getFather_age() const;
    void setFather_age(int newFather_age);
private:
    int father_age;
};
// 父类构造函数,初始化列表
TestInit::TestInit(QObject* parent, int father_age)
    : QObject { parent }
    , father_age(father_age)
{}
  • 子类:
class sonTest : public TestInit {
public:
    sonTest(TestInit* parent = nullptr, int son_age = 5);
    void printson()    {
        std::cout << "Son age is " << son_age << std::endl;
    }
private:
    int son_age;
};
// 子类构造,初始化列表
// 调用了父类初始化函数
sonTest::sonTest(TestInit* parent, int son_age)
    : TestInit(parent, parent->getFather_age())
    , son_age(son_age)
{}
  • 调用方法:
    TestInit* ti = new TestInit(nullptr, 30);
    ti->printFather();  // 输出为30
    sonTest* sonTi = new sonTest(ti, 50);
    sonTi->printFather(); // 输出为30
    sonTi->printson();  // 输出为50

2 说明

  • 父类构造函数,首先构造QObject,然后初始化父类成员

  • 子类构造时,以父类为参数,调用父类构造函数,传入合适参数

  • 调用时,首先实例化父类,初始化父对象

  • 然后,实例化子类,调用父类构造函数,以父对象作为参数

  • 最终实现父对象对子类对象的初始化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HBisnotme

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值