C++ 对象构造顺序

参考:http://blog.sina.com.cn/s/blog_4c79cc450100lkzh.html(学习对象创建和销毁的相关注意事项)

原理:先父母,再成员,后自己(成员和父母的构造函数都可以进行隐式调用,前提是构造函数为无参构造函数或默认参数构造函数,即有默认构造函数可供调用,也可以在初始化列表中显示调用)

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

 

#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

posted on   lh03061238  阅读(343)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示