C++ 多态 动态绑定

动态绑定的多态的三个条件:

1、类之间满足类型兼容规则;

2、申明虚函数

3、由成员函数来调用 或者 通过指针、引用来访问虚函数

 

 #include<iostream> using namespace std; class Shape { public: virtual void paint() { cout<<"null"<<endl; } }; class Square :public Shape { public: void paint(){ cout<<"This is a Square"<<endl; } }; class Round: public Shape { public: void paint(){ cout<<"This is a Round"<<endl; } }; void fun1(Shape & s){ // 引用 s.paint(); } void fun2(Shape * p){ // 指针 p->paint(); } int main() { Round r; Square s; fun1(r); fun1(s); fun2(&r); fun2(&s); system("pause"); }

你可能感兴趣的:(C++ 多态 动态绑定)