一杯清酒邀明月
天下本无事,庸人扰之而烦耳。
posts - 3121,comments - 209,views - 580万

一、概述

  C++中的多态性是指同一个函数可以有多种不同的实现方式,并且在运行时根据实际情况进行选择执行。在C++中实现多态有两种方式:静态多态和动态多态。静态多态是指在编译时确定函数的实现,包括函数重载和模板函数;动态多态是指在运行时根据对象的实际类型来确定函数的实现,包括虚函数和抽象类。

二、静态多态

1、函数重载

  函数重载是指在同一个作用域中定义多个同名函数,它们的参数列表不同。编译器会根据函数的参数列表唯一地确定要调用的函数。函数重载的实现可以通过编译时的函数匹配来实现,实现起来比较简单。 下面是一个函数重载的示例代码:

复制代码
 1 #include <iostream>
 2 
 3 void print(int i) {
 4     std::cout << "This is an integer: " << i << std::endl;
 5 }
 6 
 7 void print(float f) {
 8     std::cout << "This is a float: " << f << std::endl;
 9 }
10 
11 int main() {
12     print(42);
13     print(3.14f);
14     return 0;
15 }
复制代码

  上面的代码中,我们定义了两个同名的函数`print`,但是它们的参数列表不同,一个接受整数,一个接受浮点数。在调用函数`print`时,编译器会自动根据参数的类型选择调用哪个函数。

2、模板函数

  模板函数是指在定义函数时使用了类型参数,可以让函数适用于多种不同的类型。编译器会在编译时根据参数类型来生成具体的函数实现。模板函数的实现可以通过编译时的模板实例化来实现。 下面是一个模板函数的示例代码:

复制代码
 1 #include <iostream>
 2 #include <cstdlib>
 3 
 4 template <typename T>
 5 T max(T a, T b) {
 6     return a > b ? a : b;
 7 }
 8 
 9 int main() {
10     int x = 42, y = 23;
11     float f = 3.14f, g = 2.71f;
12     std::cout << "Max of " << x << " and " << y << " is " << max(x, y) << std::endl;
13     std::cout << "Max of " << f << " and " << g << " is " << max(f, g) << std::endl;
14     return 0;
15 }
复制代码

  上面的代码中,我们定义了一个模板函数`max`,它可以针对整数、浮点数等多种类型进行运算。在调用函数`max`时,编译器会根据参数类型自动推断出要使用哪个具体的函数实现。

三、动态多态

1、虚函数

  虚函数是指在基类中定义的函数可以被派生类重写的函数。通过将函数声明为虚函数,我们可以在运行时根据对象的实际类型来确定要调用的函数实现。在C++中,只要将函数声明为虚函数即可实现动态多态。 下面是一个虚函数的示例代码:

复制代码
 1 #include <iostream>
 2 
 3 class Shape {
 4 public:
 5     virtual float calculateArea() { return 0; }
 6 };
 7 
 8 class Square : public Shape {
 9 public:
10     Square(float l) : _length(l) {}
11     virtual float calculateArea() { return _length * _length; }
12 private:
13     float _length;
14 };
15 
16 class Circle : public Shape {
17 public:
18     Circle(float r) : _radius(r) {}
19     virtual float calculateArea() { return 3.14f * _radius * _radius; }
20 private:
21     float _radius;
22 };
23 
24 int main() {
25     Shape *s1 = new Square(5);
26     Shape *s2 = new Circle(3);
27     std::cout << "Area of square is " << s1->calculateArea() << std::endl;
28     std::cout << "Area of circle is " << s2->calculateArea() << std::endl;
29     delete s1;
30     delete s2;
31     return 0;
32 }
复制代码

  上面的代码中,我们定义了一个基类`Shape`和两个派生类`Square`和`Circle`,它们都实现了函数`calculateArea`。在调用函数`calculateArea`时,我们将基类指针指向派生类对象,可以看到运行时实际调用的是派生类的实现函数。

2、抽象类

  抽象类是指包含至少一个纯虚函数的类,这个类不能被实例化,只能用作基类来派生出其他类。在C++中,可以通过将函数声明为纯虚函数来实现抽象类。 下面是一个抽象类的示例代码:

复制代码
 1 #include <iostream>
 2 
 3 class Shape {
 4 public:
 5     virtual float calculateArea() = 0;
 6 };
 7 
 8 class Square : public Shape {
 9 public:
10     Square(float l) : _length(l) {}
11     virtual float calculateArea() { return _length * _length; }
12 private:
13     float _length;
14 };
15 
16 class Circle : public Shape {
17 public:
18     Circle(float r) : _radius(r) {}
19     virtual float calculateArea() { return 3.14f * _radius * _radius; }
20 private:
21     float _radius;
22 };
23 
24 int main() {
25     // Shape *s = new Shape();  // error: cannot instantiate abstract class
26     Shape *s1 = new Square(5);
27     Shape *s2 = new Circle(3);
28     std::cout << "Area of square is " << s1->calculateArea() << std::endl;
29     std::cout << "Area of circle is " << s2->calculateArea() << std::endl;
30     delete s1;
31     delete s2;
32     return 0;
33 }
复制代码

  上面的代码中,我们将基类`Shape`中的函数`calculateArea`声明为纯虚函数,从而实现了抽象类。抽象类不能被实例化,只能用作基类来派生出其他类。在调用函数`calculateArea`时,我们将基类指针指向派生类对象,可以看到运行时实际调用的是派生类的实现函数。

四、总结

  本文介绍了C++中实现运行时多态的两种方式:静态多态和动态多态。静态多态包括函数重载和模板函数,动态多态包括虚函数和抽象类。通过对这些知识点的学习,可以更好地理解C++中的多态性,更灵活地应用在实际的程序开发中。

posted on   一杯清酒邀明月  阅读(598)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2022-08-11 Qt QImage读取某些jpg或png图片失败的问题
2021-08-11 Qt 解决:fatal error C1189: #error : include 'stdafx.h' before including this file for PCH
2021-08-11 Qt error: C2440: “默认参数”: 无法从“const wchar_t [1]”转换为“BSTR”
2021-08-11 Qt 使用包含MFC的内容包含过的库
2020-08-11 Qt QPainter::end: Painter ended whith 2 saced states
2020-08-11 Qt QPixmap, QByteArray, QString互相转换
2020-08-11 Qt 绘图(QBitmap,QPixmap,QImage,QPicture)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示