问题:
我们为什么常常定义一个基类的指针,去调用派生类的成员函数?
B 15:26:12
利用多态
(来自微信: http://weixin.qq.com/q )
A 15:29:44
好处在哪里 就是不用自己重写一遍某些函数吗 ,我的意思是为什么不直接定义派生类的指针呢?
调用的时候不需要知道pBase所指的具体派生类,只要调用就Ok,这是oo的体现
#include<iostream> using namespace std; class Base { public: virtual void testFunc() { cout<<"Base"<<endl; } }; class Derived1 :public Base { public: virtual void testFunc() { cout<<"Derived1"<<endl; } }; class Derived2 :public Base { public: virtual void testFunc() { cout<<"Derived2"<<endl; } }; int main() { Base* pBase = new Derived1(); pBase->testFunc(); cout<<endl; pBase = new Derived2(); pBase->testFunc(); cout<<endl; }