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++是怎么构造函数的初始化列表的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注编程网行业资讯频道,感谢各位的阅读!