天天看点

[C++11]委托构造函数

委托构造函数允许使用同一个类中的一个构造函数调用其他的构造函数,从而简化相关变量的初始化。

注意点:

1.这种链式的构造函数调用不能形成一个闭环(死循环),否则会在运行期抛异常。

2.如果要进行多层构造函数的链式调用,建议将构造函数的调用写在初始化列表中而不是函数体内部,否则编译器会提示形参的重复定义。

3.在初始化列表中调用了代理构造函数初始化某个类成员变量之后,就不能在初始化列表中再次初始化这个变量了。

代码如下:

#include <iostream>
using namespace std;

class Test
{
public:
	Test(){}
	Test(int a)
	{
		cout << a << endl;
	}

	Test(int a, int b)
	{
		cout << a << endl;//跟Test(int a)中的代码一样
		cout << b << endl;
	}

	Test(int a, int b, int c)
	{
		cout << a << endl;//跟Test(int a,int b)中的代码一样
		cout << b << endl;//跟Test(int a,int b)中的代码一样
		cout << c << endl;
	}

	int a;
	int b;
	int c;

};
           

委托构造函数

代码如下:

#include <iostream>
using namespace std;

class Test
{
public:
	Test(){}
	Test(int a)
	{
		cout << a << endl;
	}

	Test(int a, int b):Test(a)
	{
		cout << b << endl;
	}

	Test(int a, int b, int c) :Test(a, b)
	{
		cout << c << endl;
	}

	int a;
	int b;
	int c;

};

int main()
{
	int a = 2;
	int b = 1;
	int c = 3;
	Test t(a);
	cout << "---------------" << endl;
	Test t1(a, b);
	cout << "---------------" << endl;
	Test t2(a, b, c);
	cout << "---------------" << endl;
	return 0;
}
           

测试结果:

[C++11]委托构造函数

在初始化列表中调用了代理构造函数初始化某个类成员变量之后,就不能在初始化列表中再次初始化这个变量了。

[C++11]委托构造函数
[C++11]委托构造函数

继续阅读