1.情况1,
class Base { public: ~Base() { cout << "~Base()" << endl; } };
class Derived1 : public Base { public: Derived1():name_(new string("NULL")) {} Derived1(const string& n):name_(new string(n)) {} ~Derived1() { delete name_; cout << "~Derived1(): name_ has been deleted." << endl; } private: string* name_; }; class Derived2 : public Base { public: Derived2():name_(new string("NULL")) {} Derived2(const string& n):name_(new string(n)) {} ~Derived2() { delete name_; cout << "~Derived2(): name_ has been deleted." << endl; } private: string* name_; };
我们看下面对其析构情况进行测试:
int main() { Derived1* d1 = new Derived1(); Derived2 d2 = Derived2("Bob"); delete d1; return 0; }
因为引用的类型就是派生类,所以析构函数,先删除派生类,后删除基类(建立一个派生类,一定会先建立一个基类(成员初始化列表语法)
结果:
~Derived1(): name_ has been deleted.
~Base()
~Derived2(): name_ has been deleted.
~Base()
情况二:
int main() { Base* base[2] = { new Derived1(), new Derived2("Bob") }; for (int i = 0; i != 2; ++i) { delete base[i]; } return 0; }
没有虚析构函数,所以删除引用的类型
动态绑定:http://blog.csdn.net/iicy266/article/details/11906509
基类析构虚函数:因为动态绑定,先删除析构类,后删除基类
~Base()
~Base()
情况三:
class Base { public: virtual ~Base() { cout << "~Base()" << endl; } };