虚函数、构造、析构、初始化列表
#include <iostream>
using namespace std; class Base{ public: Base(const char* p_szName):m_szName(p_szName) {cout << "Base类构造:" << m_szName << "," << endl;} virtual ~Base() {cout << "Base类析构:" << "~" << m_szName << "," << endl;} //~Base() {cout << "Base类析构:" << "~" << m_szName << "," << endl;}
private: const char* m_szName; }; class Derived:public Base{ public: Derived(const char* p_szName):m_szName(p_szName) ,m_objA((const char*)"A") ,m_objB((const char*)"B") ,Base((const char*)"C"){ cout << "Derived类构造:" << m_szName << "," << endl; } virtual ~Derived() {cout << "Derived类析构:" << "~"<< m_szName << "," << endl;} //~Derived() {cout << "Derived类析构:" << "~"<< m_szName << "," << endl;}
private: const char* m_szName; Base m_objB; Base m_objA; }; int main(){ Base* p= new Derived("D"); delete p; return 0; }
先根据继承先后关系,用C完成Base的构造,然后根据Derived成员定义的先后关系,对字符串m_szName、成员m_objB、成员m_objA进行初始化,但是对字符串m_szName初始化并不首先打印,对成员m_objB、成员m_objA初始化会调用Base的构造函数,然后才执行大括号里面的内容
Base类构造:C, Base类构造:B, Base类构造:A, Derived类构造:D, Derived类析构:~D, Base类析构:~A, Base类析构:~B, Base类析构:~C,
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。