C++11特性,构造函数的一点小例子

C++11特性,构造函数的一点小例子
1.继承构造函数
有时候,我们的基类中可能拥有数量众多的不同版本的构造函数,这时对派生类而言,写构造函数时为了构造基类,需要写很多的“透传”的构造函数,相当不方便。
C++11扩展了C++中已经有的using声明来解决此问题。c++原有的using声明的作用是:如果派生类要使用基类的成员函数的话,
可以通过using声明来完成。c++11中扩展到了构造函数,子类可以使用using声明来声明继承基类的构造函数。例如:

class A1
{
public:
	A1(int i) {}
	A1(double d, int i) {}
	A1(float f, int i, const char* c) {}
};

struct A
{
	A(int i) {}
	A(double d, int i) {}
	A(float f, int i, const char* c) {}
	// ...
};

c++11标准中继承构造函数被设计成跟派生类中的各种累默认函数(默认构造、析构、拷贝构造等)一样,是隐式声明的。
这意味着如果一个继承构造函数不被相关代码使用,编译器不会为其产生真正的函数代码,这样更加节省目标代码空间。
2.委派构造函数
小例子如下:

class Info
{
public:
	Info() { InitRest(); }
	Info(int i) : Info(){ type = i; }
	Info(char e) : Info() { name = e; }
private:
	void InitRest() { /* 其他初始化 */ }
	int type = 1;
	char name{ 'a' };
	// ...
};

class Info2
{
public:
	Info2() : Info2(1, 'a') {}
	Info2(int i) : Info2(i, 'a') {}
	Info2(char e) : Info2(1, e) {}
private:
	Info2(int i, char e) : type(i), name(e) { /* 其他初始化 */ }
	int type;
	char name;
	// ... 
};

3.综合应用,新特新与旧的方法对比:

#include <iostream>

class A 
{
public:
	A() :A(0, 'A') { std::cout << "A::void" << std::endl; }
	A(int i) :A(i, 'A') { std::cout << "A::int" << std::endl; }
	A(char c) :A(1, c) { std::cout << "A::char" << std::endl; }
	A(int i, char c) : _i(i), _c(c) { std::cout << "A::full" << std::endl; }
private:
	int _i;
	char _c;
};

class B :public A {
	using A::A;//继承构造函数
};

class C :public A {
public:
	C(int i, char c) :A(i, c) { std::cout << "C::A" << std::endl; }//以往我们使用的方法,基础用法
};



int main() {
	A();
	std::cout << std::endl;
	A(1);
	std::cout << std::endl;
	A('a');
	std::cout << std::endl;
	A(1, 'a');

	B();
	std::cout << std::endl;
	B(1);
	std::cout << std::endl;
	B('a');
	std::cout << std::endl;
	B(1, 'a');

	std::cout << std::endl;
	C(1, 'a');



	std::cin.get();
	return 0;
}

第一篇文章,才疏学浅,所写的文章十份粗陋,文章中前两个例子借鉴他人代码,非常感谢Eric的知道,有错漏之处请斧正.谢谢

猜你喜欢

转载自blog.csdn.net/weixin_43220160/article/details/84644504