深入探索C++构造函数之三:委托构造函数

委托构造函数属于c++11新标准,因此文中涉及到程序在编译时需要指定编译器类型为c++11,linux可以通过-std=c++11选项指定:
g++ test.cpp -std=c++11 -o test
1、何为委托构造函数
顾名思义,委托构造函数使用它所属类的其它构造函数执行它的初始化过程,也就是说它把它的一些(或全部)职责委托给了其它构造函数。

class testA
{
    public:
    testA(int ii,double dd):i(ii),d(dd)
    //非委托构造函数
    {
        cout<<"non delegating constructor carried out! \n";
    }
    testA():testA(0,0)
    //委托构造函数1,将初始化职责委托给非委托构造函数
    {
        cout<<"default constructor carried out!\n";
     }
    testA(string str):testA()
    //非委托构造函数2,将职责委托给委托构造函数1
    {
        cout<<"str:"<<str<<endl;
    }
    int i;
    double d;
};
testA定义了三个构造函数:
第一个构造函数为非委托构造函数,接收两个实参,使用这些实参初始化数据成员。
第二个构造函数为委托构造函数,通过委托的形式定义了一个默认构造函数,该函数调用非委托构造函数1进行构造;
第三个函数为委托构造函数,会调用委托构造函数2进行相关构造工作。

2、函数执行顺序
当一个函数委托给另一个构造函数时,受委托的构造函数的初始值列表和函数体被一次执行。

#include<iostream>
#include<string>
using namespace std;
class testA
{
    public:
    testA(int ii,double dd):i(ii),d(dd)
    //非委托构造函数
    {
        cout<<"non delegating constructor carried out! \n";
    }
    testA():testA(0,0)
    //委托构造函数1,将初始化职责委托给非委托构造函数
    {
        cout<<"default constructor carried out!\n";
     }
    testA(string str):testA()
    //非委托构造函数2,将职责委托给委托构造函数1
    {
        cout<<"str:"<<str<<endl;
    }
    int i;
    double d;
};
int main()
{
    testA A0(11,3.14);
    testA A1;
    string str="hello world";
    testA A2(str);
    return 0;
}
编译:
g++ -std=c++11 test.cpp -o test
运行结果:
non delegating constructor carried out! //对象A0调用非委托构造函数
non delegating constructor carried out!//对象A1先调用非委托构造函数
default constructor carried out!       //然后再执行自己的函数体
non delegating constructor carried out!//A2调用委托构造函数1,函数1再调用非委托
default constructor carried out!       //构造函数
str:hello world

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值