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.解决方法（初始化列表）

```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)//调用有参构造函数
```