zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Dubbo教程:入门到实战
    阿里面试Java程序员都问些什么?
    Canon MF113W激光打印机双面打印方法
    MacBook Pro App Store无法下载和更新软件解决方案
    收不到Win10正式版预订通知?一个批处理搞定
    创业公司失败的20大原因:没市场需求排第一
    最新版本sublime text3注册码
    Spring MVC 知识点整理
    Nginx子域名配置
    Install Local SQL In Mac OS
  • 原文地址:https://www.cnblogs.com/lh03061238/p/12324343.html
Copyright © 2011-2022 走看看