继承中构造函数内部的运行顺序

本文探讨了C++中派生类构造函数如何调用基类构造函数的机制。通过实例展示,当派生类构造函数未明确调用基类构造函数时,默认会调用基类的默认构造函数。此外,还解释了如何通过成员初始化列表来控制基类构造函数的调用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在C++中,派生类的构造函数内部可以显示的调用基类的构造函数,如果不显示的调用基类的构造函数,那么会默认的调用基类的默认构造函数。例如,假设基类为Item_base,定义如下:

class Item_base
{
private:
    int number;
    string str;
public:
    Item_base()
    {
        cout << "the default constructor of base class is called!\n";
    }

    Item_base(int num,string s): number(num),str(s)
    {
        cout << "the constructor of base calss is called!" << endl;
    }
    ~Item_base(){}
};
派生类定义如下所示:

class Derive_class:public Item_base
{
private:
    size_t qty;
    double price;
public:
    Derive_class()
    {
        cout << "the first default constructor is called!\n";
    }

    Derive_class(size_t q,double p): qty(q),price(p)
    {
        cout << "the second constructor of derive class is called!" << endl;
    }

    Derive_class(int num,string s,size_t q ,double p) :qty(q),price(p)
    {
        cout << "the third constructor is called!\n";
        Item_base(num,s);
    }
};
在main函数中使用基类和派生类构造对象,代码如下所示:
int main()
{
    cout << "first:\n";
    Item_base item;

    cout << "second:\n";
    Item_base new_item(4,"hello");

    cout << "third:\n";
    Derive_class derive;

    cout << "fourth:\n";
    Derive_class new_derive(5,6.2);

    cout << "fifth:\n";
    Derive_class new_derive2(6,"world",3,4.2);

    return 0;
}
运行mian函数,输出结果为:
first:
the default constructor of base class is called!
second:
the constructor of base calss is called!
third:
the default constructor of base class is called!
the first default constructor is called!
fourth:
the default constructor of base class is called!
the second constructor of derive class is called!
fifth:
the default constructor of base class is called!
the third constructor is called!
the constructor of base calss is called!
从程序运行结果可以看出,在构造派生类对象时总是先调用基类构造函数构造基类部分的对象,在派生类的构造函数中如果没有显示的调用基类的构造函数,那么派生类构造函数机会隐式的调用基类的默认构造函数。而且,在派生类的构造函数中,函数体内的代码只能对基类部分的对象进行赋值,基类对象的构造是在进入函数体内以前完成的。如果将派生类的最后一个构造函数改为如下:
Derive_class(int num,string s,size_t q ,double p) :Item_base(num,s),qty(q),price(p)
{
   cout << "the third constructor is called!\n";
}
那么main函数的输出将变为:
first:
the default constructor of base class is called!
second:
the constructor of base calss is called!
third:
the default constructor of base class is called!
the first default constructor is called!
fourth:
the default constructor of base class is called!
the second constructor of derive class is called!
fifth:
the constructor of base calss is called!
the third constructor is called!
可见,在派生类的成员初始化列表中调用基类构造函数就可以阻止派生类构造函数隐式的调用基类默认构造函数。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值