欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-04 13:59:45
目录1.问题2.解决方法(初始化列表)3.顺序问题总结1.问题class a {private:int m_a;public:a(int a) {cout << "a(int a).......

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++构造函数的初始化列表详解

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

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);
}

运行结果:

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

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);
}

结果:

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

跟下面顺序有关:

private:
	a m_a2;
	a m_a1;

跟下面顺序无关:

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

总结

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