多态是什么?简单来说,就是某段程序调用了一个API接口,但是这个API有许多种实现,根据上下文的不同,调用这段API的程序,会调用该API的不同实现。今天我们只关注继承关系下的多态。
#include <iostream> #include <stdio.h> using namespace std; class Father { public: int m_fid; Father() { m_fid = 1; } virtual void v_print() { printf("Father v_print() %d ", m_fid); } void print() { printf("Father print() %d ", m_fid); } }; class Child : public Father { public: int m_cid; Child() { m_cid = 2; } void v_print() { printf("Child v_print() %d:%d ", m_fid, m_cid); } void print() { printf("Child print() %d:%d ", m_fid, m_cid); } }; int main(void) { Father *f = new Father(); Father *fc = new Child(); Child *c = new Child(); Child *cf = (Child*)new Father(); f->print(); f->v_print(); fc->print();//静态 fc->v_print();//动态 c->print(); c->v_print(); cf->print();//静态 cf->v_print();//动态 return 0; }
运行结果为:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Father print() 1 Father v_print() 1 Father print() 1 Child v_print() 1:2 Child print() 1:2 Child v_print() 1:2 Child print() 1:0 Father v_print() 1