【问题标题】:Difference between overriding and overloading of a function in C++ [duplicate]C ++中函数的覆盖和重载之间的区别[重复]
【发布时间】:2015-03-16 16:12:03
【问题描述】:

我正在我的大学学习 c plus plus 课程,我无法区分函数的覆盖和重载,谁能帮助我。

【问题讨论】:

  • 如果我理解你的问题,这完全不一样。覆盖:重新定义子类中的函数(多态、继承)。重载:在单个类中公开许多具有相同名称但不同签名的函数(参数列表)。希望对您有所帮助。
  • 我在答案中还没有看到的一点:覆盖允许您定义具有相同名称的不同方法。它们可以有不同的签名,并且在调用时会选择正确的方法版本。另一方面,在覆盖时,覆盖的方法必须具有相同的签名。

标签: c++


【解决方案1】:

这是foo 的两个不同的重载

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

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

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      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
      

      【讨论】:

        【解决方案4】:

        覆盖意味着,对具有相同参数的现有函数给出不同的定义, 而重载意味着为现有函数添加不同的定义,并带有不同的参数。

        例子:

        #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
        

        【讨论】:

          猜你喜欢
          • 2016-06-01
          • 2022-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-28
          • 2020-03-05
          • 2012-08-08
          • 2013-02-14
          相关资源
          最近更新 更多