1、模板实现
实例
class CRectangle
{
public:
void Draw() {
cout<<"CRectangle:Draw()"<<endl;
}
};
template<class T>
class CShape
{
public:
void Draw(T* t) {
t->Draw();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CCircle oCircle;
CShape<CCircle> oShape1;
oShape1.Draw(&oCircle);
CRectangle oRectangle;
CShape<CRectangle> oShape2;
oShape2.Draw(&oRectangle);
return 0;
}
2、虚函数
如果基类中的函数是虚函数,那么集成类默认也是虚函数
class CCircle: public CShape
{
public:
//如果基类是虚函数,那么集成类默认也是虚函数,可以无限传递下去
void Draw() {
cout<<"CCircle:Draw()"<<endl;
}
};
class CRectangle:public CShape
{
public:
//如果基类是虚函数,那么集成类默认也是虚函数,可以无限传递下去
void Draw() {
cout<<"CRectangle:Draw()"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CShape *pShape1 = new CRectangle();
pShape1->Draw(); //打印“CRectangle:Draw()”
CShape *pShape2 = new CCircle();
pShape2->Draw(); //打印“CCircle:Draw()”
return 0;
}