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的拷贝函数会报错
	}
};

错误:


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

将class B构造函数改写为:


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

完整代码如下:


#include <iostream>
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);
}

运行结果:

3.顺序问题

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

例子:


class A {
private:
	int m_a;
public:
	A(int a) {
		cout << "A(int a)......." <<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_a2;
	A m_a1;
public:
	B(int a1, int a2, int b) :m_a1(a1), m_a2(a2)//调用有参构造函数
	{
		cout << "B(int a1, int a2, int b)......." << endl;
		m_b = b;
	}
	~B() {
		cout << "~B()......." << endl;
	}
};
int main(int argc, char** argv) {
	B b2(1, 2, 3);
}

结果:


跟下面顺序有关:


private:
	A m_a2;
	A m_a1;

跟下面顺序无关:


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

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程学习网的更多内容!

本文标题为:C++构造函数的初始化列表详解

基础教程推荐