有如下程序: #include<iostream> using namespace std; class TestClass { public: virtual void fun1() { cout<<"fun1TestClass"; } virtual void fun2() { cout<<"fun2TestClass"; } }; class TestClass1:public TestClass { void fun() { cout<<"fun1TestClass1"; } void fun2(int x) { cout<<"fun2TestClass1"; } }; int main() { TestClass obj1,*p; TestClass1 obj2; p=&obj2; p->fun1(); p->fun2(); return 0; } 该程序执行后的输出结果是( )。
A.fun1TestClass1 fun2TestClass
B.fun1TestClass1 fun2TestClass1
C.fun1TestClass fun2TestClass
D.fun1TestClass fun2TestClass1
参考答案:A
解析: TestClass为基类,Testclass1是TestClass的派生类。基类中的fun1和fun2被定义为虚函数,C++规定,当一个成员函数被声明为虚函数后,其派生类中的同名函数都自动成为虚函数,所以派生类中的fun1和tim2也是虚函数。本题从main主函数入手,首先定义了TestClass类型的对象obj1和指针p,然后又定义了TestClass1的对象obi2。指针指向对象obi2,然后调用其成员函数 fun1(),即输出“fun1TcstClass1”。 多态性是在程序运行过程中才动态地确定操作指针指向的对象,“p->fun2();”语句中没有任何参数,并不是调用派生类中的fun2(int x),而是调用其基类中的fun2(),所以输出“fun2TestClass”。