zoukankan      html  css  js  c++  java
  • 有继承情形下 基类与子类的构造函数与析构函数运行顺序

    有继承情形下 基类与子类的构造函数与析构函数运行顺序,如下代码:

    #include "stdafx.h"
    #include
    using namespace std;
    class A {
    public:
    A() {
    cout << "Base class constructor" << endl;
    ~A() {
    cout << "Base class destructor" << endl;
    }
    };
    class B : public A {
    public:
    B() {
    cout << "Subclass constructor" << endl;
    }
    ~B() {
    cout << "Subclass Destructor" << endl;
    }
     
    };
    void function() {
    B b;
    }
     
    int main()
    {
    function();
    while (1);
        return 0;
    }
    试运行代码查看结果,而知基类与子类构造函数与析构函数的顺序。
    注:在派生类中,若基类构造函数含有参数(有关内容可参考我的博客或网上其它解释),则必须有子类构造函数且说明基类构造函数,其代码如下:
    #include "stdafx.h"
    #include
    #include
    #include
    using namespace std;
    class A {
    public:
    A(int c) {
    cout << "c=" <<c<< endl;
    }                                                                                     //此为含参构造函数
    ~A() {
    cout << "come  on" << endl;
    }
    public:
    int c;
    };
    class B : public A {
    public:
    B(int c ,int b):A(c) {
    cout << "b="<<b<< endl;
    }                                                                                        //此为子类含参构造函数
    ~B() {
    cout << "Subclass Destructor" << endl;
    }
    private:
    int b;
    };
    int main()
    {
    B bb(10,100);                                                           //此种用法相关解释,可见我的博客
    while (1);
        return 0;
    }
    仔细比较下一个代码与上一个代码:
    #include "stdafx.h"
    #include
    #include
    #include
    using namespace std;
    class A {
    public:
    A(int c) {
    cout << "c=" <<c<< endl;
    }                                                                                             //此为含参构造函数
    ~A() {
    cout << "come  on" << endl;
    }
    public:
    int c;
    };
    class B : public A {
    public:
    B(int c ,int b);                                                           //此为子类含参构造函数
    ~B() {
    cout << "Subclass Destructor" << endl;
    }
    private:
    int b;
    };
     
    B::B(int c ,int b):A(c) {
    cout << "b="<<b<< endl;
    }                                                 //类外写函数,A(c)表示调用基类构造函数,故而无数据类型
     
     
     
    int main()
    {
    B bb(10,100);           //此种用法相关解释,可见我的博客
    while (1);
        return 0;
    }
     
    点亮希望! 
  • 相关阅读:
    vue cli3使用官方方法配置sass全局变量报错ValidationError: Invalid options object. Sass Loader has been initialised using an options object that does not match the API schema.
    面试必备:HashMap、Hashtable、ConcurrentHashMap的原理与区别
    Lombok介绍、使用方法和总结
    位运算
    【ZooKeeper系列】3.ZooKeeper源码环境搭建
    【ZooKeeper系列】2.用Java实现ZooKeeper API的调用
    【ZooKeeper系列】1.ZooKeeper单机版、伪集群和集群环境搭建
    弄明白CMS和G1,就靠这一篇了
    面试官,不要再问我三次握手和四次挥手
    【面试必备】小伙伴栽在了JVM的内存分配策略。。。
  • 原文地址:https://www.cnblogs.com/tangjunjun/p/11676654.html
Copyright © 2011-2022 走看看