委托构造函数属于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