c++: C++中重载和覆盖的区别

1. 重载(overload)

理论

  • 函数组成一般格式是:
return_type function_name( parameter list )
  • 重载指的是函数具有的不同的参数或者不同返回值,而函数名必须相同的函数。简单说出了function_name其他都可以不同:
  • 重载要求输入参数列表或者返回值必须不同比如:
    – 输入参数的类型不同,或者同时(输出返回值不同)
    – 输入参数的个数不同,或者同时(输出返回值不同)
    – 输入参数的顺序不同,或者同时(输出返回值不同)

  • 程序是根据参数列表来确定具体要调用哪个函数的

以下6个函数都可以构成函数重载

void Fun(int a);
void Fun(double a);
void Fun(int a, int b);
void Fun(double a, int b);
int Fun(float a, int b);
float Fun(float a);

以下2个是无法构成函数重载的,因为参数列表必须不同

void Fun(int a)
float Fun(int a)

例子

下面的例子是重载构造函数:3次

#include <iostream>
using namespace std;

class Status
{
    public:
        int code_;
        Status():code_(2){cout << "list init code: "<< code_ << endl;}//构造函数不能有返回值
        ~Status();
        Status(int a)//构造函数不能有返回值
        {
                cout << "int Fun(int a)"<< a << endl;
        }

        Status(float a)//构造函数不能有返回值
        {
                cout << "void Fun(float a)"<< a << endl;
        }

        int Fun(int a)//不同返回值,不同输入参数
        {
                cout << "void Fun(int a)"<< a << endl;
                return a;
        }
        float Fun(float a)//不同返回值,不同输入参数
        {
                cout << "void Fun(float a)"<< a << endl;
                return a;
        }
        //int Fun(float a) //不同返回值,相同输入参数,将无法重载因为输入的参数和float Fun(float a)一样,系统无法区分
        //{
        //        cout << "void Fun(float a)"<< a << endl;
        //        return 1;
        //}
};

实现:

int main(int argc, char **argv)
{
        Status *pfun = new Status();
        Status *pfun1 = new Status(9);
        Status *pfun2 = new Status(0.1f);
        cout << pfun1->Fun(3) << endl;
        cout << pfun2->Fun(0.3f) << endl;
        cout << "#########" << endl;
        cout << "code_ "<< pfun->code_ <<endl;
        cout << "code_ "<< pfun1->code_ <<endl;
        cout << "code_ "<< pfun2->code_ <<endl;
        return 0;
}

结果

list init code: 2
int Fun(int a)9
void Fun(float a)0.1
void Fun(int a)3
3
void Fun(float a)0.3
0.3
#########
code_ 2
code_ 0
code_ 0

2. 覆盖(重写override)

  • 定义:覆盖只能在继承过程中,覆盖基类的虚函数或者纯虚函数,正常函数不能被覆盖。

  • 特征:继承过程中覆盖的时候子类和基类的函数名返回值参数列表必须和基类相同

  • 调用:当子类的对象调用成员函数的时候:

    • 如果基类的成员函数被覆盖调用子类中的成员函数
    • 如果基类的成员函数没有被覆盖,则调用从基类继承过来的函数

3. 重载和覆盖的区别

  1. 重载: 要求函数名相同,但是参数列表必须不同返回值可以相同也可以不同

    覆盖: 要求函数名、参数列表、返回值必须相同。

  2. 重载: 是同一个类不同成员函数之间的关系。

    覆盖: 是子类基类之间不同成员函数之间的关系。

  3. 重载: 函数的调用是根据参数列表来决定调用哪一个函数。

    覆盖: 函数的调用是根据对象类型的不同决定调用哪一个。

  4. 重载:在类中对成员函数重载是不能够实现多态

    覆盖:在子类中对基类虚函数的覆盖可以实现多态

猜你喜欢

转载自blog.csdn.net/dinnerhowe/article/details/79931602
今日推荐