码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 对象构造顺序

时间:2020-02-17 23:49:10      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:ring   end   iostream   对象   ace   object   clu   include   parent   

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

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

 

#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

C++ 对象构造顺序

标签:ring   end   iostream   对象   ace   object   clu   include   parent   

原文地址:https://www.cnblogs.com/lh03061238/p/12324343.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!