看《C++ Template》一书中才发现使用模板也可以实现多态,所不同的是模板灵活性不如抽象类,但是是静态编译的,因此效率要高。 #include<iostream> class Shape { public: virtual void draw() const = 0; }; class Circle:public Shape { public: virtual void draw() const; }; void Circle::draw() const { std::cout<<"Circle draw()"<<std::endl; } class Line:public Shape { public: virtual void draw() const; }; void Line::draw() const { std::cout<<"Line draw()"<<std::endl; } //Using inheritance to realize polymorphism void mydraw(Shape& obj) { obj.draw(); } //Using template to realize polymorphism template<typename T> void template_draw(T& obj) { obj.draw(); } int main(void) { Line l; Circle c; //Shape s; //abstract class cannot be realized mydraw(l); mydraw(c); template_draw(l); template_draw(c); return 0; }