您的位置:首页 > 其它

构造函数、初始化列表的调用顺序

2015-03-22 20:58 846 查看
#include <iostream>

using namespace std;

class ParentA

{

public:

ParentA()

{

cout << "construct A" << endl;

}

ParentA(const ParentA &pa)

{

cout << "copy construct A " << index << endl;

}

~ParentA()

{

cout << "unconstruct A" << endl;

}

};

class ClassB

{

public:

ClassB(int b)

{

cout << "construct B:"<<b << endl;

}

~ClassB()

{

cout << "unconstruct B" << endl;

}

};

class ChildC:ParentA

{

public:

ChildC() :b1(1),b2(2) //无论 b1(1),b2(2) 的顺序如何调换,对于先构造谁后构造谁没有影响

{

cout << "construct c" << endl;

}

~ChildC()

{

cout << "unconstruct c" << endl;

}

private:

ClassB b2; // 声明 b1,b2 的顺序 直接影响他们初始化的顺序

ClassB b1;

};

void main(char **argv, int arg)

{

ChildC c;

}

输出结果:

construct A //先构造 父类

construct B:2 // 构造成员 ,按照成员声明的顺序 构造 与 构造函数列表中的顺序无关

construct B:1

construct c

unconstruct c

unconstruct B

unconstruct B

unconstruct A

ParentA f(ParentA u)
{
ParentA v(u);
ParentA w = v;
return w;
}
void main() {
ParentA x(1);
f(x);// 调用四次
ParentA y = f(f(x));// 只有7次,不是把八次
}


中间 f(x) -> f(
f(x) ) 时,省了一次
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: