把公用的放到基类,把不同的放到子类中实现,实现功能的共享。
1 #ifndef Template_H_H 2 #define Template_H_H 3 4 #include <iostream> 5 #include <string> 6 using namespace std; 7 8 class Base{ 9 public: 10 void show(){ 11 cout << "This is " << getName() << endl; 12 } 13 virtual string getName() = 0; 14 }; 15 16 class A : public Base{ 17 public: 18 virtual string getName(){ return "ClassA"; } 19 }; 20 21 class B : public Base{ 22 public: 23 virtual string getName(){ return "ClassB"; } 24 }; 25 26 void TemplateTest(){ 27 Base *base1 = new A(); 28 base1->show(); 29 30 Base *base2 = new B(); 31 base2->show(); 32 33 delete base1; 34 delete base2; 35 } 36 37 #endif