【为什么】到底什么是多态?

简介: 【为什么】到底什么是多态?

“多态性”(polymorphism)一词意味着具有多种形式。 简单来说,我们可以将多态性定义为消息以多种形式展示的能力。

多态性的一个真实例子是一个人可以同时具有不同的特征。 男人同时是父亲、丈夫和雇员。 所以同一个人在不同的情况下会表现出不同的行为。 这称为多态性。 多态性被认为是面向对象编程的重要特征之一。

多态性的类型

    • 编译时的多态性
    • 运行时的多态性

    image.gif编辑

    1.编译时多态性

    这种类型的多态性是通过函数重载或运算符重载来实现的。

    A. 函数重载

    当有多个同名但参数不同的函数时,这些函数被称为 重载, 因此这被称为函数重载。 来重载函数 可以通过更改参数数量 或/和 更改参数类型 。 简单来说,它是面向对象编程的一个特点,当许多任务列在一个函数名称下时,它提供许多具有相同名称但不同参数的函数。 某些 函数重载规则,重载函数时应遵循

    下面是显示函数重载或编译时多态性的 C++ 程序:

    // C++ program to demonstrate
    // function overloading or
    // Compile-time Polymorphism
    #include <bits/stdc++.h>
    using namespace std;
    class Geeks {
    public:
      // Function with 1 int parameter
      void func(int x)
      {
        cout << "value of x is " <<
            x << endl;
      }
      // Function with same name but
      // 1 double parameter
      void func(double x)
      {
        cout << "value of x is " <<
            x << endl;
      }
      // Function with same name and
      // 2 int parameters
      void func(int x, int y)
      {
        cout << "value of x and y is " <<
            x << ", " << y << endl;
      }
    };
    // Driver code
    int main()
    {
      Geeks obj1;
      // Function being called depends
      // on the parameters passed
      // func() is called with int value
      obj1.func(7);
      // func() is called with double value
      obj1.func(9.132);
      // func() is called with 2 int values
      obj1.func(85, 64);
      return 0;
    }

    image.gif

    输出

    value of x is 7
    value of x is 9.132
    value of x and y is 85, 64

    image.gif

    解释: 在上面的例子中,一个名为 function func() 的函数在三种不同的情况下表现不同,这是多态性的一个特性。

    B. 运算符重载

    C++ 能够为运算符提供对数据类型的特殊含义,这种能力称为运算符重载。 例如,我们可以使用字符串类的加法运算符 (+) 来连接两个字符串。 我们知道这个运算符的任务是将两个操作数相加。 因此,单个运算符“+”,当放在整数操作数之间时,将它们相加,当放在字符串操作数之间时,将它们连接起来。

    下面是演示运算符重载的 C++ 程序:

    // C++ program to demonstrate
    // Operator Overloading or
    // Compile-Time Polymorphism
    #include <iostream>
    using namespace std;
    class Complex {
    private:
      int real, imag;
    public:
      Complex(int r = 0,
          int i = 0)
      {
        real = r;
        imag = i;
      }
      // This is automatically called
      // when '+' is used with between
      // two Complex objects
      Complex operator+(Complex const& obj)
      {
        Complex res;
        res.real = real + obj.real;
        res.imag = imag + obj.imag;
        return res;
      }
      void print()
      {
      cout << real << " + i" <<
          imag << endl;
      }
    };
    // Driver code
    int main()
    {
      Complex c1(10, 5), c2(2, 4);
      // An example call to "operator+"
      Complex c3 = c1 + c2;
      c3.print();
    }

    image.gif

    输出

    12 + i9

    image.gif

    解释: 在上面的例子中,运算符'+'被重载了。 通常,此运算符用于将两个数(整数或浮点数)相加,但此处使该运算符执行两个虚数或复数的相加。

    2. 运行时多态性

    这种类型的多态性是通过 Function Overriding 实现的。 后期绑定和动态多态是运行时多态的其他名称。 函数调用在运行时 多态性 中在运行时解析。 相反,对于编译时多态性,编译器在运行时推导后确定将哪个函数调用绑定到对象。

    A. 函数覆盖

    当派生类具有基类的成员函数之一的定义时,就会发生函数覆盖。 据说该基本功能已被覆盖。

    image.gif编辑

    下面是演示函数覆盖的 C++ 程序:

    // C++ program for function overriding
    #include <bits/stdc++.h>
    using namespace std;
    class base {
    public:
      virtual void print()
      {
        cout << "print base class" <<
            endl;
      }
      void show()
      {
      cout << "show base class" <<
          endl;
      }
    };
    class derived : public base {
    public:
      // print () is already virtual function in
      // derived class, we could also declared as
      // virtual void print () explicitly
      void print()  
      {
        cout << "print derived class" <<
            endl;
      }
      void show()
      {
      cout << "show derived class" <<
          endl;
      }
    };
    // Driver code
    int main()
    {
      base* bptr;
      derived d;
      bptr = &d;
      // 虚函数绑定在
      // 运行时 (Runtime polymorphism)
      bptr->print();
      // 非虚函数绑定在
      // 编译时
      bptr->show();
      return 0;
    }

    image.gif

    输出

    print derived class
    show base class

    image.gif

    虚函数

    一个虚函数是 在基类中使用关键字virtual声明并在派生类中重新定义(Overridden)的成员函数。

    关于虚函数的一些要点:

    *虚函数本质上是动态的。
    *插入关键字“ virtual ”来定义的,并且总是用基类声明并在子类中被覆盖 它们是通过在基类中
    *在运行时调用虚函数

    image.gif

    下面是演示虚函数的C++程序:

    // C++ Program to demonstrate
    // the Virtual Function
    #include <iostream>
    using namespace std;
    // Declaring a Base class
    class GFG_Base {
    public:
      // virtual function
      virtual void display()
      {
        cout << "Called virtual Base Class function" <<
            "\n\n";
      }
      void print()
      {
        cout << "Called GFG_Base print function" <<
            "\n\n";
      }
    };
    // Declaring a Child Class
    class GFG_Child : public GFG_Base {
    public:
      void display()
      {
        cout << "Called GFG_Child Display Function" <<
            "\n\n";
      }
      void print()
      {
        cout << "Called GFG_Child print Function" <<
            "\n\n";
      }
    };
    // Driver code
    int main()
    {
      // Create a reference of class GFG_Base
      GFG_Base* base;
      GFG_Child child;
      base = &child;
      // This will call the virtual function
      base->GFG_Base::display();
      // this will call the non-virtual function
      base->print();
    }

    image.gif

    输出

    Called virtual Base Class function
    Called GFG_Base print function
    相关文章
    |
    3月前
    |
    网络协议 Linux C++
    Window 部署 coze-stdio(coze 开发平台)
    本指南介绍了如何在本地环境部署 Coze Studio,包括环境配置、镜像源设置、模型配置及服务启动步骤。内容涵盖 Docker 配置、模型添加方法及常见问题解决方案,适用于 Windows 11 系统,需最低 2 核 CPU 和 4GB 内存。
    1307 8
    Window 部署 coze-stdio(coze 开发平台)
    |
    存储 Linux 开发工具
    告别Hugging Face模型下载难题:掌握高效下载策略,畅享无缝开发体验
    【8月更文挑战第2天】告别Hugging Face模型下载难题:掌握高效下载策略,畅享无缝开发体验
    2180 64
    告别Hugging Face模型下载难题:掌握高效下载策略,畅享无缝开发体验
    |
    SQL JSON JavaScript
    JavaWeb基础9——VUE,Element&整合Javaweb的商品管理系统
    Vue 指令、生命周期、this和$、vue脚手架进行模块化开发/ElementUI框架、综合案例,element商品列表展示增删改查
    JavaWeb基础9——VUE,Element&整合Javaweb的商品管理系统
    |
    存储 运维 监控
    |
    XML Java 数据处理
    深入了解 XPath
    【8月更文挑战第22天】
    276 0
    |
    数据可视化 Python
    Seaborn中的时间序列图:展示数据随时间的变化趋势
    【4月更文挑战第17天】使用Seaborn创建时间序列图可展现数据随时间变化的趋势。首先,确保数据集包含日期时间格式的时间戳字段。借助Pandas处理数据,然后使用Seaborn的`lineplot`创建基本图表。通过`line_kws`自定义线条样式,添加标题和轴标签以增强可视化。结合Pandas的`rolling`计算滚动平均值,`resample`进行数据重采样,或使用Statsmodels进行时间序列分析和预测,从而提升图表功能和分析深度。有效定制图表有助于更好地理解和传达数据趋势。
    |
    机器学习/深度学习
    |
    Linux Python
    CentOS7安装Python3.8
    CentOS7安装Python3.8
    644 0
    CentOS7安装Python3.8
    |
    存储 负载均衡 网络协议
    Nacos 注册中心
    Nacos(全称为 "Dynamic Naming and Configuration Service")是一个用于实现动态服务发现、服务配置和服务管理的开源项目。它由阿里巴巴集团开发和维护,是一种基于云原生理念构建的服务注册和配置中心。 Nacos 提供了以下主要功能:
    269 0
    |
    SQL 关系型数据库 MySQL
    mysql基本查询、运算符、排序和分页
    mysql基本查询、运算符、排序和分页
    106 0