Chinaunix首页 | 论坛 | 博客
  • 博客访问: 27190
  • 博文数量: 3
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 68
  • 用 户 组: 普通用户
  • 注册时间: 2013-11-15 01:02
文章分类

全部博文(3)

文章存档

2014年(2)

2013年(1)

我的朋友

分类: C/C++

2014-08-07 00:53:14


点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;
  3. class Door
  4. {
  5. public:
  6.     virtual void Open() { cout<<"I'm a thinly pathetic shelter, just kick me\n"<<endl; } //运行时的多态性,如果不加virtual就是编译时的多态
  7. //    void Open() { cout<<"I'm a thinly pathetic shelter, just kick me\n"<<endl; }//编译时的多态性
  8. };

  9. class SaftyDoor:public Door
  10. {
  11. public:
  12.     void Open()
  13.     {
  14.         cout<<"Look at the key hole, do you have the key?\n"<<endl;
  15.     }
  16. };

  17. class SteelDoor:public SaftyDoor
  18. {
  19. public:
  20.     void Open()
  21.     {
  22.         cout<<"Kick? you little pathetic comic\n"<<endl;
  23.     }
  24. };

  25. //还可以调用祖宗的Open()
  26. class FakeDoor:public SaftyDoor
  27. {
  28. public:
  29.     void Open()
  30.     {
  31.         cout<<"I am new and splendid, BUT still ";
  32.         Door::Open();
  33.     }
  34.     //假冒伪劣安全门糊弄人的新功能
  35.     void Alert()
  36.     {
  37.         cout<<"bee bee bee bee....\n"<<endl;
  38.     }
  39. };

  40. void main()
  41. {
  42.     while(1)
  43.     {
  44.         Door* door_BoughtWhenIAmPoor = new Door();
  45.         Door* door_BoughtWhenIEarnedMoney = new SaftyDoor();
  46.         Door* door_BoughtWhenIAmRich = new SteelDoor();
  47.         Door* door_BoughtWhenIWatchedDoorAds = new FakeDoor();

  48.         door_BoughtWhenIAmPoor->Open();
  49.         door_BoughtWhenIEarnedMoney->Open();
  50.         door_BoughtWhenIAmRich->Open();
  51.         door_BoughtWhenIWatchedDoorAds->Open();
  52.         
  53.         delete door_BoughtWhenIAmPoor;
  54.         delete door_BoughtWhenIEarnedMoney;
  55.         delete door_BoughtWhenIAmRich;
  56.         delete door_BoughtWhenIWatchedDoorAds;

  57.         cin.get();
  58.     }
  59. }



运行结果




--------------------------------------------------------------------------------------------------------------------

最近在工作中用了几套三方SDK写程序, 发现一个特点, 这几套SDK在使用上都一个风格, 形如本例

本例是由百度百科里的例子改来的, 原例都是A,B,C莫名其妙的变量名, 函数名, 难看!

改成这样就好多了, 有助理解.

--------------------------------------------------------------------------------------------------------------------

结论:
1.    这种风格似乎使程序更好扩展, 子类可以重写属于自己的方法, 也可以调用父类或祖宗类的方法, 而却用祖宗类的类型定义
2.    由于用的是指针, 所以可以实现动态分配类占的空间, 随时释放


阅读(2489) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~