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,然后初始化父类成员
-
子类构造时,以父类为参数,调用父类构造函数,传入合适参数
-
调用时,首先实例化父类,初始化父对象
-
然后,实例化子类,调用父类构造函数,以父对象作为参数
-
最终实现父对象对子类对象的初始化