C++ 初始化列表

在C++构造函数中,我们一般倾向于将类成员放在初始化列表中进行,但需要注意的是初始化的顺序必须与成员声明顺序保持一致,否则在成员相互依赖时会发送不可预知的错误;另外在函数体中通过上两篇文章我们知道构造函数会完成虚表的构造,另成员在初始化列表中只需调用复制构造函数而在函数体中可能会生成临时对象(根据初始化类型而定),调用赋值函数操作,这样一来就增加了调用开销,降低了效率。测试代码如下:

#include <iostream>

using namespace std;

class A {
private:
	int i;
	int j;

public:
	A(int value):j(value),i(j+1) {
		cout << "i:" << i << ",j:" << j << endl;
	}

	~A() {

	}
};

class B {
public:
	B() {
		cout << "B:B()" << endl;
	}
	
	B(int i) {
		cout << "B:B(int)" << endl;
	}

	B(const B &b) {
		cout << "B(const B&b)" << endl;
	}

	B& operator=(const B &b) {
		cout << "B& operator=(const B &b)" << endl;
	}
};

class D {
public:
	virtual int size() {
		cout << "D::size()" << endl;
		return 0;
	}
};

class C:A,D{
private:
	int c;
	B b;
public:
	C(int value):c(this->size()),A(value) { 
		b = value;
		cout << "C:C()" << ",c:" << c << endl;
	}

	int size() {
		cout << "C::size()" << endl;
		return 1;
	}
};

int main(int argc,char *argv[]) {
	//A a(1);
	C c(1);
	return 0;
}

  运行结果如下:

test_con
i:4200913,j:1
C::size() //任何对象初始化前先执行初始化成员列表
B:B()
B:B(int)
B& operator=(const B &b)
C:C(),c:1

上面的例子可以看出,成员初始化列表中,保持声明顺序的同时也需要注意调用非初始化成员否则同样会引起不可预知的错误。

posted on 2015-07-09 13:27  kkford  阅读(236)  评论(0编辑  收藏  举报

导航