C++ 对象构造顺序

原理:先父母,再成员,后自己

          注意:可以结合默认参数的构造函数(相当于同时提供了有参构造函数和无参构造函数)

#include <iostream>
#include <string>

using namespace std;

class Obj
{
string ms;
public:
Obj(string s="hello Obj")
{
cout << "Obj(string s) : " << s << endl;
ms = s;
}

~Obj()
{
cout << "~Obj() : " << ms << endl;
}
};

class Object
{
string ms;


public:
Object(string s="hello Object")
{
cout << "Object(string s) : " << s << endl;
ms = s;
}
~Object()
{
cout << "~Object() : " << ms << endl;
}
};

class Parent : public Object
{
string ms;
Obj Obj_1;
Obj Obj_2;
public:
Parent() : Object("Default")

{
cout << "Parent()" << endl;
ms = "Default";
}
Parent(string s) : Object(s), Obj_1(s), Obj_2(s)
{
cout << "Parent(string s) : " << s << endl;
ms = s;
}
~Parent()
{
cout << "~Parent() : " << ms << endl;
}
};

class Child : public Parent
{
Object mO1;
Object mO2;
string ms;
public:
Child() : mO1("Default 1"), mO2("Default 2")
{
cout << "Child()" << endl;
ms = "Default";
}
Child(string s) : Parent(s), mO1(s + " 1"), mO2(s + " 2")
{
cout << "Child(string s) : " << s << endl;
ms = s;
}
~Child()
{
cout << "~Child() " << ms << endl;
}
};

int main()
{

Child aa;

Child cc("cc");

cout << endl;

return 0;
}

运行结果:

Object(string s) : Default
Obj(string s) : hello Obj
Obj(string s) : hello Obj
Parent()
Object(string s) : Default 1
Object(string s) : Default 2
Child()
Object(string s) : cc
Obj(string s) : cc
Obj(string s) : cc
Parent(string s) : cc
Object(string s) : cc 1
Object(string s) : cc 2
Child(string s) : cc

~Child() cc
~Object() : cc 2
~Object() : cc 1
~Parent() : cc
~Obj() : cc
~Obj() : cc
~Object() : cc
~Child() Default
~Object() : Default 2
~Object() : Default 1
~Parent() : Default
~Obj() : hello Obj
~Obj() : hello Obj
~Object() : Default

猜你喜欢

转载自www.cnblogs.com/lh03061238/p/12324343.html