Object initialization list in c ++

 

The reason (1) object initialization list that appears

       1. You must do this:

        If we have a class member, which itself is a class or a structure, but it has only one member of this constructor arguments, no default constructor (). This time to be a member of this class initialization, it must call the constructor with parameters of the class members, if there is no initialization list, then he will not be able to complete the first step, it will error.

 

       2, class members if const modification must be initialized when the object, to const int m assignment. When the class member contains a const object, or when a quote is, they must be initialized by the member initialization list because the two objects to be initialized immediately after the statement, but in the constructor, to do for them assignment, this is not allowed.

 

(2) c ++ initialization list provided to member variables are initialized, grammar rules:

        

Constructor::Contructor() : m1(v1), m2(v1,v2), m3(v3)
{
    // some other assignment operation
}

 

(3) Note that the concept of

     Initialization: initialize the object being created

     Assignment: The object is assigned already exists

 

(4) the initialization order of the corresponding parameter list constructor:

   Sequence The initialization sequence and declare member variables related to, regardless of the order in the initialization list, initialize a list of executed before the constructor function body.

 

The execution sequence and execution destructor (5) opposite the constructor

   

Code is as follows, seriously look at the output:

#include<iostream>
using namespace std;


class A
{
public:


	A(int _a)
	{
		a = _a;
		cout<<"构造函数"<<" a "<<a<<endl;
	}

	~A()
	{
		cout<<"析构函数"<<" a "<<a<<endl;
	}  
	void print()
	{
		cout << a << endl;
	}
	
protected:

private:
	int a;
};


//1 构造函数的初始化列表  解决: 在B类中 组合了一个 A类对象 (A类设计了构造函数)
//根据构造函数的调用规则 设计A的构造函数, 必须要用;没有机会初始化A
//新的语法  Constructor::Contructor() : m1(v1), m2(v1,v2), m3(v3)
class B
{
public:
	B(int _b1, int _b2):a1(1),a2(2),c(0)
	{

	}

	B(int _b1, int _b2, int m, int n):a1(m), a2(n), c(0)
	{
		b1 = _b1;
		b2 = _b2;
		cout<<"B的构造函数"<<endl;
	}

	~B()  //c++中的析构函数,没有返回值,不允许加任何参数,故不能重载
	{
		cout << "B的析构函数" << endl;
	}
	
private:
	int b1;
	int b2;
	A a2;
	A a1;
	const int c;
};


//2 在初始化参数列表中,先执行初始化参数列表的构造函数,再执行下面构造函数的部分
//如果组合对象有多个,按照定义顺序,而不是按照初始化列表的顺序

//析构函数:和执行构造函数的顺序正好相反

//3 被组合对象的构造顺序,与定义顺序有关,与初始化列表的顺序没有关系
//4 初始化列表用来给const属性赋值

void obj10play()
{
	//A a1(10);
	//B objB(1,2);

	// 1 参数传递
	B objB2(1, 2, 3, 4);

	//2 调用顺序
}


int main(int argc, char* argv[])
{
	obj10play();
	system("pause");
}

/**
输出:
构造函数 a 4
构造函数 a 3
B的构造函数
B的构造函数
析构函数 a 3
析构函数 a 4
请按任意键继续....
*/

 

 

He published 199 original articles · won praise 77 · Views 200,000 +

Guess you like

Origin blog.csdn.net/tianguiyuyu/article/details/104023026