写出下面函数的正确输出结果:
- #if (__GNUC__ > 2)
- #include <iostream>
- using std::cerr;
- using std::cout;
- using std::endl;
- using std::flush;
- #else
- #include <iostream.h>
- #endif
- using namespace std;
- class Base{public:
- virtual void f(float x){ cout << "Base::f(float) " << x << endl; }
- void g(float x){ cout << "Base::g(float) " << x << endl; }
- void h(float x)={ cout << "Base::h(float) " << x << endl; }
- };
-
- class Derived : public Base{
- public:
- virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }
- void g(int x){ cout << "Derived::g(int) " << x << endl; }
- void h(float x){ cout << "Derived::h(float) " << x << endl; }
- };
- int main(void){
- Derived d;//派生类对象
- Base *pb = &d;
- Derived *pd = &d;
- pb->f(3.14f);//由virtual 虚函数重写,基类指针指向派生类对象,从而实现多态
- pd->f(3.14f);
- pb->g(3.14f);//基类和派生类都定义了“相同名称之函数”,那么通过对象指针调用成员函数时,到底调用了那个函数,必须视该指针的原始类型而定,而不是视指针实际所指的对象的类型而定
- pd->g(3.14f); //pd 原型为派生类,所以调用派生类的成员函数
-
- pb->h(3.14f);
- pd->h(3.14f);
- return 1;
- }
该题考查了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]#
阅读(601) | 评论(0) | 转发(0) |