题目
编写一个包含三个重载虚函数的类。从中继承一个新类并重写其中一个函数。
创建派生类的对象。你能通过派生类对象调用所有基类函数吗?
将对象的地址向上转换到基。你能通过基调用所有三个函数吗?
删除派生类中重写的定义。现在可以通过派生类对象调用所有基类函数了吗?
代码
#include<iostream>
using namespace std;
class A
{
public:
virtual void fun1(){cout<<"A::fun1()"<<endl;}
virtual void fun2(){cout<<"A::fun2()"<<endl;}
virtual void fun3(){cout<<"A::fun3()"<<endl;}
};
class B: public A
{
public:
//void fun1(){cout<<"B::fun1()"<<endl;}
};
int main()
{
B test;
//通过派生类对象调用基类所有函数
cout <<"through the derived-class object:"<<endl;
test.fun1();
test.fun2();
test.fun3();
//通过指针基调用所有函数
cout<<"through the base:"<<endl;
A* p = & test;
p->fun1();
p->fun2();
p->fun3();
return 0;
}