区分 C++ 中的函数重载和函数覆盖?
11 回答
在 C++ 中重载方法(或函数)是定义同名函数的能力,只要这些方法具有不同的签名(不同的参数集)。方法重写是继承类重写基类的虚方法的能力。
a)在重载中,同一类中可用的方法之间存在关系,而在覆盖中,超类方法和子类方法之间存在关系。
(b) 重载不会阻止从超类继承,而重写会阻止从超类继承。
(c) 在重载中,不同的方法共享相同的名称,而在重写中,子类方法替换超类。
(d) 重载必须有不同的方法签名,而重写必须有相同的签名。
当您想要具有不同参数的相同函数时,会完成函数重载
void Print(string s);//Print string
void Print(int i);//Print integer
函数重写是为了给基类中的函数赋予不同的含义
class Stream//A stream of bytes
{
public virtual void Read();//read bytes
}
class FileStream:Stream//derived class
{
public override void Read();//read bytes from a file
}
class NetworkStream:Stream//derived class
{
public override void Read();//read bytes from a network
}
当您更改方法签名中参数的原始类型时,您正在实施重载。
当您更改派生类中方法的原始实现时,您正在放置一个覆盖。
重载意味着对具有相同参数的现有函数给出不同的定义,而重载意味着对具有不同参数的现有函数添加不同的定义。
例子:
#include <iostream>
class base{
public:
//this needs to be virtual to be overridden in derived class
virtual void show(){std::cout<<"I am base";}
//this is overloaded function of the previous one
void show(int x){std::cout<<"\nI am overloaded";}
};
class derived:public base{
public:
//the base version of this function is being overridden
void show(){std::cout<<"I am derived (overridden)";}
};
int main(){
base* b;
derived d;
b=&d;
b->show(); //this will call the derived overriden version
b->show(6); // this will call the base overloaded function
}
输出:
I am derived (overridden)
I am overloaded
1.函数重载是当一个类中存在多个同名函数时。函数覆盖是指函数在基类和派生类中具有相同的原型。
2.函数重载可以在没有继承的情况下发生。当一个类继承自另一个类时,就会发生函数覆盖。
3.重载的函数要么参数数量不同,要么参数类型不同。在重写的函数参数必须相同。
有关更多详细信息,您可以访问下面的链接,您可以在其中获得有关 c++ 中的函数重载和覆盖的更多信息 https://googleweblight.com/i?u=https://www.geeksforgeeks.org/function-overloading-vs-function-覆盖-in-cpp/&hl=en-IN
函数重载是同名函数,但参数不同。函数覆盖意味着同名函数和参数相同
Function overloading
- 具有相同名称但参数数量不同的函数
Function overriding
- 继承的概念。具有相同名称和相同数量参数的函数。据说第二个函数覆盖了第一个函数
在重载具有不同参数的具有相同名称的函数中,而在具有相同名称和相同参数的覆盖函数中,将基类替换为派生类(继承类)
函数重载可能具有不同的返回类型,而函数覆盖必须具有相同或匹配的返回类型。
重载意味着拥有相同名称但不同签名的方法覆盖意味着重写基类的虚拟方法......
除了现有的答案之外,覆盖的函数在不同的范围内;而重载的函数在同一范围内。