函数重载通过改变签名来提供函数的多种定义,即改变参数的数量,改变参数的数据类型,返回类型不起作用。它可以在基类和派生类中完成。
例子:

void area(int a);
void area(int a, int b);

示例代码:

// CPP program to illustrate
// Function Overloading
#include <iostream>
using namespace std;

// overloaded functions
void test(int);
void test(float);
void test(int, float);

int main()
{
    int a = 5;
    float b = 5.5;

    // Overloaded functions
    // with different type and
    // number of parameters
    test(a);
    test(b);
    test(a, b);

    return 0;
}

// Method 1
void test(int var)
{
    cout << "Integer number: " << var << endl;
}

// Method 2
void test(float var)
{
    cout << "Float number: "<< var << endl;
}

// Method 3
void test(int var1, float var2)
{
    cout << "Integer number: " << var1;
    cout << " and float number:" << var2;
}

运行结果:

Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5

函数重写(在运行时实现)
函数重写是基类函数在其派生类中的重新定义,具有相同的签名,即返回类型和参数。它只能在派生类中完成。
例子:

Class a
{
public: 
      virtual void display(){ cout << "hello"; }
};

Class b:public a
{
public: 
       void display(){ cout << "bye";}
};

示例代码:

// CPP program to illustrate
// Function Overriding
#include<iostream>
using namespace std;

class BaseClass
{
public:
    virtual void Display()
    {
        cout << "\nThis is Display() method"\n                " of BaseClass";
    }
    void Show()
    {
        cout << "\nThis is Show() method "\n            "of BaseClass";
    }
};

class DerivedClass : public BaseClass
{
public:
    // Overriding method - new working of
    // base class's display method
    void Display()
    {
        cout << "\nThis is Display() method"\n            " of DerivedClass";
    }
};

// Driver code
int main()
{
    DerivedClass dr;
    BaseClass &bs = dr;
    bs.Display();
    dr.Show();
}

运行结果:

This is Display() method of DerivedClass
This is Show() method of BaseClass

函数重载 VS 函数覆盖:

  • 继承:当一个类从另一个类继承时,就会发生函数的覆盖。 重载可以在没有继承的情况下发生。
  • 函数签名:重载函数的函数签名必须不同,即参数数量或参数类型应该不同。 在函覆盖中,函数签名必须相同。
  • 功能范围:被覆盖的功能在不同的范围内; 而重载的函数在同一范围内。
  • 函数的行为:当派生类函数必须做一些与基类函数不同的工作时,需要覆盖。 重载用于具有相同名称的函数,这些函数的行为取决于传递给它们的参数。