-
#include <iostream>
-
using namespace std;
-
class Door
-
{
-
public:
-
virtual void Open() { cout<<"I'm a thinly pathetic shelter, just kick me\n"<<endl; } //运行时的多态性,如果不加virtual就是编译时的多态
-
// void Open() { cout<<"I'm a thinly pathetic shelter, just kick me\n"<<endl; }//编译时的多态性
-
};
-
-
class SaftyDoor:public Door
-
{
-
public:
-
void Open()
-
{
-
cout<<"Look at the key hole, do you have the key?\n"<<endl;
-
}
-
};
-
-
class SteelDoor:public SaftyDoor
-
{
-
public:
-
void Open()
-
{
-
cout<<"Kick? you little pathetic comic\n"<<endl;
-
}
-
};
-
-
//还可以调用祖宗的Open()
-
class FakeDoor:public SaftyDoor
-
{
-
public:
-
void Open()
-
{
-
cout<<"I am new and splendid, BUT still ";
-
Door::Open();
-
}
-
//假冒伪劣安全门糊弄人的新功能
-
void Alert()
-
{
-
cout<<"bee bee bee bee....\n"<<endl;
-
}
-
};
-
-
void main()
-
{
-
while(1)
-
{
-
Door* door_BoughtWhenIAmPoor = new Door();
-
Door* door_BoughtWhenIEarnedMoney = new SaftyDoor();
-
Door* door_BoughtWhenIAmRich = new SteelDoor();
-
Door* door_BoughtWhenIWatchedDoorAds = new FakeDoor();
-
-
door_BoughtWhenIAmPoor->Open();
-
door_BoughtWhenIEarnedMoney->Open();
-
door_BoughtWhenIAmRich->Open();
-
door_BoughtWhenIWatchedDoorAds->Open();
-
-
delete door_BoughtWhenIAmPoor;
-
delete door_BoughtWhenIEarnedMoney;
-
delete door_BoughtWhenIAmRich;
-
delete door_BoughtWhenIWatchedDoorAds;
-
-
cin.get();
-
}
-
}
运行结果
--------------------------------------------------------------------------------------------------------------------
最近在工作中用了几套三方SDK写程序, 发现一个特点, 这几套SDK在使用上都一个风格, 形如本例
本例是由百度百科里的例子改来的, 原例都是A,B,C莫名其妙的变量名, 函数名, 难看!
改成这样就好多了, 有助理解.
--------------------------------------------------------------------------------------------------------------------
结论:
1. 这种风格似乎使程序更好扩展, 子类可以重写属于自己的方法, 也可以调用父类或祖宗类的方法, 而却用祖宗类的类型定义
2. 由于用的是指针, 所以可以实现动态分配类占的空间, 随时释放
阅读(2489) | 评论(0) | 转发(1) |