函数体与函数调用相联系称为捆绑。晚捆绑又称为动态捆绑或运行时捆绑。为了引起晚捆绑,c++要求在基类中声明这个函数时使用virtual关键字。
不把析构函数设为虚函数是一个隐匿的错误,因为它常常不会对程序有直接的影响。但会不知不觉地引入存储器泄露。
#include <iostream> #include <vector> class Shape { public: virtual void draw() = 0; virtual ~Shape() { std::cout<<"~Shape. "; } }; class Circle : public Shape { public: void draw() { std::cout<<"Circle::draw "; } ~Circle() { std::cout<<"~Circle "; } }; class Triangle : public Shape { public: void draw() { std::cout<<"Triangle::draw. "; } ~Triangle() { std::cout<<"~Triangle "; } }; class Square : public Shape { public: void draw() { std::cout<<"Square::draw. "; } ~Square() { std::cout<<"~Square "; } }; int main() { std::cout<<"sizeof(Shape): "<<sizeof(Shape)<<" "; std::cout<<"sizeof(void *): "<<sizeof(void *)<<" "; typedef std::vector<Shape*> Container; typedef Container::iterator Iter; Container shapes; shapes.push_back(new Circle); shapes.push_back(new Square); shapes.push_back(new Triangle); for(Iter i=shapes.begin(); i!=shapes.end(); i++) (*i)->draw(); for(Iter j=shapes.begin(); j!=shapes.end(); j++) delete *j; return 0; }