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)//調用有參構造函數

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: