C++中派生类的结构和析构顺序详解
派生类因为要挪用基类, 所以结构和析构都是凭据必然顺序举办;
结构的顺序是: 基(base) -> 派生(derived);即先结构基类, 再结构派生类;
因为 基类 是独立于派生类的, 即不会挪用派生类中的工具, 所以应该先被生成;
假如派生类先于基类生成, 则因为无法挪用基类资源, 大概生成失败;
析构的顺序是: 派生(derived) -> 基(base); 即先释放派生类, 再释放基类;
因为 派生类 需要先释放挪用的基类资源, 所以应该优先释放;
假如基类先析构, 则有大概某些资源被派生类占用, 大概导致析构失败;
派生类的结构和析构顺序正好相反;
代码:
/* * CppPrimer.cpp * * Created on: 2013.11.12 * Author: Caroline */ /*eclipse cdt*/ #include <iostream> #include <string> #include <vector> #include <memory> #include <cstddef> using namespace std; class Quote { public: //Quote() = default; Quote() { std::cout << "this is Quote constructor" << std::endl; } Quote (const std::string& book, double sales_price) : bookNo (book), price (sales_price) {} std::string isbn() const { return bookNo; } virtual double net_price (std::size_t n) const { return n* price; } //虚函数 //virtual ~Quote() = default; //动态绑定析构器 virtual ~Quote() { std::cout << "this is Quote destructor" << std::endl; } private: std::string bookNo; protected: //受掩护范例 double price = 0.0; }; /*this is Quote constructor this is Disc_quote constructor this is Bulk_quote constructor this is Bulk_quote destructor this is Disc_quote destructor this is Quote destructor作者:csdn博客 Spike_King