Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1124760
  • 博文数量: 177
  • 博客积分: 761
  • 博客等级: 上士
  • 技术积分: 1518
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-04 22:37
文章分类

全部博文(177)

文章存档

2017年(1)

2016年(3)

2015年(33)

2014年(48)

2013年(60)

2012年(32)

分类: C/C++

2012-11-27 11:39:15

     写出下面函数的正确输出结果:

点击(此处)折叠或打开

  1. #if (__GNUC__ > 2)
  2. #include <iostream>
  3. using std::cerr;
  4. using std::cout;
  5. using std::endl;
  6. using std::flush;
  7. #else
  8. #include <iostream.h>
  9. #endif

  10. using namespace std;

  11. class Base{public:
  12.     virtual void f(float x){ cout << "Base::f(float) " << x << endl; } 
  13.     void g(float x){ cout << "Base::g(float) " << x << endl; }
  14.     void h(float x)={ cout << "Base::h(float) " << x << endl; }
  15. };

  16.  

  17. class Derived : public Base{
  18. public:
  19.    virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }
  20.    void g(int x){ cout << "Derived::g(int) " << x << endl; }
  21.    void h(float x){ cout << "Derived::h(float) " << x << endl; }
  22. };


  23. int main(void){
  24.     Derived d;//派生类对象
  25.     Base *pb = &d;
  26.     Derived *pd = &d;
  27.     pb->f(3.14f);//由virtual 虚函数重写,基类指针指向派生类对象,从而实现多态
  28.     pd->f(3.14f);

  29.     pb->g(3.14f);//基类和派生类都定义了“相同名称之函数”,那么通过对象指针调用成员函数时,到底调用了那个函数,必须视该指针的原始类型而定,而不是视指针实际所指的对象的类型而定
  30.     pd->g(3.14f); //pd 原型为派生类,所以调用派生类的成员函数
  31.      
  32.     pb->h(3.14f); 
  33.     pd->h(3.14f);
  34.     return 1;
  35. }
该题考查了c++的基础知识,基类与派生类之间的关系,基类与派生类实现的多态(virtual的应用)
g++编译后执行结果为
[root@localhost linuxstudy]# ./teituo 
Derived::f(float) 3.14
Derived::f(float) 3.14
Base::g(float) 3.14
Derived::g(int) 3
Base::h(float) 3.14
Derived::h(float) 3.14
[root@localhost linuxstudy]# 

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