博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C/CPP-继承的构造函数

Posted on 2023-03-13 09:36  乔55  阅读(15)  评论(0编辑  收藏  举报

如何将基类的构造函数继承给派生类

class A
{
public:
    int i;
    int j;
    A(int i1, int j1){ }
};
class B :public A
{
public:
    // using:让某个名字在当前作用域内可见。
    // 此处using语句,会将基类的每个构造函数,都主动生成一个与之对应的派生类构造函数
    // 若基类中有默认构造参数时,编译器遇到using时,会在派生类中构造出多个构造函数
    // 1、构造的第一个构造函数是带有所有参数的构造函数
    // 2、其余的构造函数,每个分别省略掉一个默认参数
    
    // 若基类中有多个构造函数,则多数情况下,派生类会继承所有的构造函数,但如下情况便外:
    // 1、若派生类中定义的构造函数与基类构造函数有相同的参数列表,则从基类中继承来的构造函数会被覆盖,相当于只继承了基类的部分构造函数
    // 2、默认、拷贝、移动构造函数不会被继承
    // 3、若派生类中只含有using从基类中继承来的构造函数,则编译器会为派生类生成默认构造函数

    using A::A; 
};

多重继承如何编写构造函数

// 继承自父类的成员直接用父类的构造函数初始化即可
// 隐式地使用基类的构造函数来初始化派生类
// 某基类存在无参构造函数,则派生类的初始化列表中可省略该基类
// 如f1无参构函,son(int i,int j,int k):father2(j),x_s(k)
// 爷爷类
class grand
{
public:
    int x_g;
    grand(int i) :x_g(i)	
    { cout << "grand" << endl;}
    virtual ~grand(){}
    void my(){cout << "x_g=" << x_g << endl;}
};

// 父类1
class father1 :public grand
{
public:
    int x_f1; 
    father1(int i):grand(i),x_f1(i){cout << "father1" << endl;}
    virtual ~father1(){}
    void my(){cout << "x_f1=" << x_f1 << endl;}
};

// 父类2
class father2
{
public:
    int x_f2;
    father2(int i) :x_f2(i){cout << "father2" << endl;}
    virtual ~father2()
    {}
    void my(){cout << "x_f2=" << x_f2 << endl;}
};

// 子类
class son :public father1, public father2
{
public:
    int x_s;
    // 每个派生类只需负责继承自直接基类的成员的初始化,此处grnad无须son来负责
    son(int i,int j,int k):father1(i),father2(j),x_s(k){cout << "son" << endl;}
    virtual ~son(){}
    void my(){cout << "x_s=" << x_s << endl;}
};
void test()
{
    son s(10, 20, 30); // 构函的调用顺序时g,f1,f2,s,析构相反
    s.my();
    s.grand::my();
    s.father1::my();
    s.father2::my();
}