Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4235365
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-05-26 14:53:36

  1. #include <iostream>

  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.     void output();
  7. };

  8. void A::output()
  9. {
  10.     cout << "a" << endl;
  11. }

  12. class B:public A
  13. {
  14. public:
  15.     void output();
  16. };

  17. void B::output()
  18. {
  19.     cout << "b" << endl;
  20. }

  21. class C:public B
  22. {
  23. public:
  24.     void output();
  25. };

  26. void C::output()
  27. {
  28.     cout << "c" << endl;
  29. }

  30. int main()
  31. {
  32.     A a;
  33.     a.output();

  34.     B b;
  35.     b.output();

  36.     C c;
  37.     c.output();

  38.     return 0;
  39. }


结果输出 a b c

  1. 修改main函数之后,输出 a a a
  2. int main()
  3. {
  4.     A a, *p;
  5.     p = &a;
  6.     p->output();

  7.     B b;
  8.     p = &b;
  9.     p->output();

  10.     C c;
  11.     p = &c;
  12.     p->output();

  13.     return 0;
  14. }

  1. 再次修改 类A ,输出 a b c
  2. #include <iostream>

  3. using namespace std;
  4. class A
  5. {
  6. public:
  7.       virtual void output();
  8. };

虚函数作用:相对于继承类,减少了继承类中,继承相同的函数,减少同一个函数或者变量 内存的消耗

附件代码: class.rar  

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