动态多态与静态多态
动态多态与静态多态
动态多态与静态多态概述动态多态(动态绑定):即运行时的多态,在程序执行期间(非编译期)判断所引用对象的实际类型,根据其实际类型调用相应的方法,在发生继承中,对父类中的带有virtual修饰的函数进行重写,类似于Java中的接口。静态多态:也称为编译期间的多态,编译器在编译期间完成的,在发生继承中,对父类的同名函数进行重定义(虚函数除外),重定义只用函数名相同即可,其他均可不同,
动态多态与静态多态
概述
- 动态多态(动态绑定):即运行时的多态,在程序执行期间(非编译期)判断所引用对象的实际类型,根据其实际类型调用相应的方法,在发生继承中,对父类中的带有
virtual
修饰的函数进行重写,类似于Java中的接口。 - 静态多态:也称为编译期间的多态,编译器在编译期间完成的,在发生继承中,对父类的同名函数进行重定义(虚函数除外),重定义只用函数名相同即可,其他均可不同,就会将父类的同名函数屏蔽,这个时候想要访问父类的同名函数的话,需要加上作用域。
静态多态实现方式:
- 函数重载:包括普通函数的重载和成员函数的重载
- 函数模板的使用
案例讲解
动态多态
学习代码
代码语言:javascript代码运行次数:0运行复制#include<iostream>
using namespace std;
class A
{
public:
A(){
}
virtual ~A(){
cout << "A discontruct" << endl;
}
virtual string OnPaint() = 0; // 定义接口
};
class B : public A
{
public:
virtual string OnPaint()
{
cout<< "B" << endl;
return "B";
}
virtual ~B(){
cout << "B discontruct" << endl;
}
};
class C : public A
{
public:
virtual string OnPaint()
{
cout<< "C" << endl;
return "C";
}
virtual ~C(){
cout << "C discontruct" << endl;
}
};
int main()
{
A* p = new B();
p->OnPaint(); // B
delete p;
p = new C();
p->OnPaint(); // C
delete p;
return 0;
}
运行结果
静态多态
学习代码
- 使用模板
// 交换两个值,但是不清楚是int 还是 double,如果不使用模板,则要写两份代码
// 使用函数模板,将类型作为参数传递
template<class T>
class Swa(T a,T b)
{
T temp;
temp = a;
a = b;
b = temp;
};
- 继承关系
#include<iostream>
using namespace std;
class A
{
public:
A(){
}
~A(){
}
void OnPaint(){
cout << "A" << endl;
}
};
class B : public A
{
public:
string OnPaint()
{
cout<< "B" << endl;
return "B";
}
};
class C : public A
{
public:
string OnPaint()
{
cout<< "C" << endl;
return "C";
}
};
int main()
{
// 静态多态的函数返回值等等都可以改变
A* p = new B();
p->OnPaint(); // A
delete p;
p = new C();
p->OnPaint(); // A
delete p;
return 0;
}
运行结果
#感谢您对电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格的认可,转载请说明来源于"电脑配置推荐网 - 最新i3 i5 i7组装电脑配置单推荐报价格
上传时间: 2025-07-19 21:36:29
推荐阅读
留言与评论(共有 9 条评论) |
本站网友 嘉峪关酒店 | 13分钟前 发表 |
对父类的同名函数进行重定义(虚函数除外) | |
本站网友 油饼的热量 | 16分钟前 发表 |
编译器在编译期间完成的 | |
本站网友 卢锡城 | 6分钟前 发表 |
A(){ } ~A(){ } void OnPaint(){ cout << "A" << endl; } }; class B | |
本站网友 新华联丽港 | 10分钟前 发表 |
对父类的同名函数进行重定义(虚函数除外) | |
本站网友 东方冠郡 | 13分钟前 发表 |
将类型作为参数传递 template<class T> class Swa(T a | |
本站网友 网上音乐 | 18分钟前 发表 |
public A { public | |
本站网友 糖尿病中医 | 2分钟前 发表 |
public A { public | |
本站网友 张明明 | 0秒前 发表 |
对父类的同名函数进行重定义(虚函数除外) |