C++中函数的重写和重载之间的区别

Difference between overriding and overloading of a function in C++

本文关键字:重载 之间 区别 重写 函数 C++      更新时间:2023-10-16

我正在大学学习 c plus plus 课程,我无法区分函数的覆盖和重载,任何人都可以帮助我。

以下是两种不同的foo重载

void foo(int);
void foo(char);

这里B::bar是一个函数覆盖

class A {
public:
    virtual void bar();
};
class B : public A {
public:
    void bar() override;
};

载意味着具有不同参数的同名函数,它实际上并不取决于您使用的是过程语言还是可以进行重载的面向对象语言。 就覆盖而言,这意味着我们正在显式定义一个存在于派生类的基类中的函数.显然,您需要面向对象的语言来执行覆盖,因为它是在基类和派生类之间完成的。

重载意味着在同一作用域中声明多个具有相同名称的函数。它们必须具有不同的参数类型,并且在编译时根据参数的静态类型选择合适的重载。

void f(int);
void f(double);
f(42);   // selects the "int" overload
f(42.0); // selects the "double" overload

重写意味着派生类声明与基类中声明的虚函数匹配的函数。 通过指针或对基类的引用调用函数将根据对象的动态类型在运行时选择重写。

struct Base {
    virtual void f();
};
struct Derived : Base {
    void f() override;  // overrides Base::f
};
Base * b = new Base;     // dynamic type is Base
Base * d = new Derived;  // dynamic type is Derived
b->f();   // selects Base::f
d->f();   // selects Derived::f

覆盖意味着,给出具有相同参数的现有函数的不同定义,重载意味着使用不同的参数添加现有函数的不同定义。

例:

#include <iostream>
class base{
    public:
    virtual void show(){std::cout<<"I am base";} //this needs to be virtual to be overridden in derived class
    void show(int x){std::cout<<"nI am overloaded";} //this is overloaded function of the previous one
    };
class derived:public base{
    public:
    void show(){std::cout<<"I am derived";}  //the base version of this function is being overridden
    };

int main(){
    base* b;
    derived d;
    b=&d;
    b->show();  //this will call the derived version
    b->show(6); // this will call the base overloaded function
    }

输出:

I am derived
I am overloaded