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