|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 这是她 于 2020-5-17 21:24 编辑
The kind of beauty i want most is the hard-to-get kind that comes from within——strenght,courage,dignity. ---Ruby Dee
多态
分类:
1、静态多态:函数重载和运算符重载属于静态多态,复用函数名
2、动态多态:派生类和虚函数实现运行时多态
静态多态和动态多态的区别:
1、静态多态的函数地址早绑定,编译阶段确定函数地址;
2、动态多态的函数地址晚绑定,运行阶段确定函数地址;
- #include<iostream>
- using namespace std;
- class Figure
- {
- public:
- void Show_a()
- {
- cout << "Figure::Show_a!!!!!!!!" << endl;
- }
-
- //虚函数----------Show_b 函数就是虚函数
- //虚函数---在函数前面加上virtual关键字变成虚函数------这样编译器在编译的时候就不能确定函数调用了,在运行阶段确定
- virtual void Show_b()
- {
- cout << "Figure::Show_b!!!!!!!!!!" << endl;
- }
- };
- //函数重写-----函数返回值类型、函数名、参数列表 完全一致
- class Diamond : public Figure
- {
- public:
- void Show_a()
- {
- cout << "Diamond::Show_a!!!!!!!!!" << endl;
- }
-
- void Show_b()
- {
- cout << "Diamond::Show_b!!!!!!!!!" << endl;
- }
- };
- class Square : public Figure
- {
- public:
- void Show_a()
- {
- cout << "Square::Show_a!!!!!!!!!!!" << endl;
- }
-
- void Show_b()
- {
- cout << "Square::Show_b!!!!!!!!!!!" << endl;
- }
- };
- //地址早绑定--在编译阶段就确定了函数地址
- //父类的指针或引用---指向于类对象
- void Doshow_a(Figure & figure)
- {
- figure.Show_a();
- }
- //地址晚绑定--在运行阶段确定函数地址
- //你想传入什么对象,就可以调用什么对象的函数
- void Doshow_b(Figure * figure)
- {
- figure->Show_b();
- }
- //动态多态满足条件:
- //1、有继承关系;
- //2、子类重写父类的虚函数;
- //动态多态使用
- //父类的指针或引用指向子类对象;
- int main()
- {
- Diamond d1;
- Doshow_a(d1);
-
- Square s1;
- Doshow_a(s1);
-
- cout << "---------------------------------------" << endl;
-
- Diamond d2;
- Doshow_b(&d2);
-
- Square s2;
- Doshow_b(&s2);
-
- return 0;
- }
复制代码 运行结果:
- Figure::Show_a!!!!!!!!
- Figure::Show_a!!!!!!!!
- ---------------------------------------
- Diamond::Show_b!!!!!!!!!
- Square::Show_b!!!!!!!!!!!
复制代码
渣渣来报道求大佬指点
|
|