zoukankan      html  css  js  c++  java
  • C++中构造函数和析构函数(virtual)的执行顺序

    using namespace std;

    class People
    {
    public:
        People(){
            cout << " Output from the structor of calss People!" << endl;
        };  // 构造函数
        virtual ~People(){
            cout << " Output from the destructor of calss People!" << endl;
        }; // 析构函数
        virtual void doSomething()
        {
            cout << "Do something in class People!" << endl;
        };

    };

    class Student : public People
    {
    public:
        Student(){
            cout << " Output from the structor of calss Student!" << endl;
        }; // 构造函数

        ~Student(){
            cout << " Output from the destructor of calss Student!" << endl;
        };// 析构函数
        void doSomething(){
            cout << "Do something in class Student!" << endl;
        };

    }

    int main() {

    Student *stu1 = new Student();
        stu1->doSomething();
        delete stu1;

        cout << endl;

        People *stu2 = new Student();
        stu2->doSomething();
        delete stu2;
        return 0;

    }


    执行结果:

    stu1:

     Output from the structor of calss People!
     Output from the structor of calss Student!
    Do something in class Student!
     Output from the destructor of calss Student!
     Output from the destructor of calss People!
    stu2:
     Output from the structor of calss People!
     Output from the structor of calss Student!
    Do something in class Student!
     Output from the destructor of calss Student!
     Output from the destructor of calss People!

  • 相关阅读:
    p4841 城市规划
    p2619 [国家集训队2]Tree I [wqs二分学习]
    p3723 [AH2017/HNOI2017]礼物
    p5437 【XR-2】约定
    p5349 幂
    数据结构:结构之美
    你所不知道的传输层
    为什么选择这种技术而不选择另一种技术?
    Internet路由-主机路由表和转发表
    计算机网络----数据链路层(三)
  • 原文地址:https://www.cnblogs.com/bbsno1/p/3270904.html
Copyright © 2011-2022 走看看