C++构造函数的初始化列表详解

1.问题

class A {
private:
	int m_a;
public:
	A(int a) {
		cout << "A(int a)......." << endl;
		m_a = a;
	}
	void print() {
		cout <<"m_a=" << m_a << endl;
	}
};
class B {
private:
	int m_b;
	A m_a1;
	A m_a2;
public:
	B(A& a1,A& a2, int b) 
	{
		m_b = b;
		m_a1(a1);//此处调用A的拷贝函数会报错
		m_a2(a2);//此处调用A的拷贝函数会报错
	}
};

错误:

C++构造函数的初始化列表详解_第1张图片

C++构造函数的初始化列表详解_第2张图片

2.解决方法(初始化列表)

将class B构造函数改写为:

public:
	B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//构造函数的初始化列表
	{
		m_b = b;
	}
};

完整代码如下:

#include 
using namespace std;
class A {
private:
	int m_a;
public:
	A(int a) {
		cout << "A(int a)......." << endl;
		m_a = a;
	}
	void print() {
		cout <<"m_a=" << m_a << endl;
	}
	A(const A& another) {
		m_a = another.m_a;
	}
	~A() {
		cout << "~A()......" << endl;
	}
};
class B {
private:
	int m_b;
	A m_a1;
	A m_a2;
public:
	B(A& a1,A& a2, int b) :m_a1(a1),m_a2(a2)//构造函数的初始化列表,调用拷贝构造
	{
		cout << "B(A& a1,A& a2, int b)......." << endl;
		m_b = b;
	}
	~B() {
		cout << "~B()......." << endl;
		cout << "m_b=" << m_b  << endl;
		cout << "A m_a1" << endl;
		m_a1.print();
		cout << "A m_a2" << endl;
		m_a2.print();
	}
};
int main(int argc, char** argv) {
	A a1(1), a2(2);
	B b1(a1, a1, 3);
}

运行结果:

C++构造函数的初始化列表详解_第3张图片

3.顺序问题

构造对象成员的顺序跟初始化列表的顺序无关,而是跟成员对象定义的顺序有关。(面试会问)

例子:

class A {
private:
	int m_a;
public:
	A(int a) {
		cout << "A(int a)......." < 
 

结果:

C++构造函数的初始化列表详解_第4张图片

跟下面顺序有关:

private:
	A m_a2;
	A m_a1;

跟下面顺序无关:

B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//调用有参构造函数

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

你可能感兴趣的:(C++构造函数的初始化列表详解)