C++编程思想 第1卷 第15章 多态性和虚函数 重载和重新定义 析构函数和虚拟析构函数

析构函数是不能为虚函数的。但析构函数能够且常常必须是虚的

构造函数有一项特殊工作,即一块一块地组合成一个对象

构造函数和析构函数是类层次进行调用的唯一地方

通常,析构函数的执行是相当充分的

如果这个指针是指向基类的,在delete期间,编译器只能知道调用这个析构
函数的基类版本

//: C15:VirtualDestructors.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Behavior of virtual vs. non-virtual destructor
#include <iostream>
using namespace std;

class Base1 {
public:
  ~Base1() { cout << "~Base1()\n"; }
};

class Derived1 : public Base1 {
public:
  ~Derived1() { cout << "~Derived1()\n"; }
};

class Base2 {
public:
  virtual ~Base2() { cout << "~Base2()\n"; }
};

class Derived2 : public Base2 {
public:
  ~Derived2() { cout << "~Derived2()\n"; }
};

int main() {
  Base1* bp = new Derived1; // Upcast
  delete bp;
  Base2* b2p = new Derived2; // Upcast
  delete b2p;
  getchar();
} ///:~

当运行这个程序时,将会看到delete bp只调用基类的构造函数

即使析构函数像构造函数一样,是“例外”函数,但析构函数可以是虚的,
这是因为这个对象已经知道它是什么类型。一旦对象已被构造,它的VPTR
就已被初始化,所以能发生虚函数调用

输出
~Base1()
~Derived2()
~Base2()

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81353706