Pra*_*d G 75
在C++中重载方法(或函数)是能够定义相同名称的函数,只要这些方法具有不同的签名(不同的参数集).方法重写是继承类重写基类的虚方法的能力.
a)在重载时,同一类中可用的方法之间存在关系,而在重写时,超类方法和子类方法之间存在关系.
(b)重载不会阻止超类的继承,而是覆盖超类的继承.
(c)在重载时,单独的方法共享相同的名称,而在重写中,子类方法替换超类.
(d)重载必须具有不同的方法签名,而重写必须具有相同的签名.
Ani*_*dha 20
当您希望具有不同参数的相同功能时,将完成功能重载
void Print(string s);//Print string
void Print(int i);//Print integer
Run Code Online (Sandbox Code Playgroud)
函数重写是为了给基类中的函数赋予不同的含义
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
}
Run Code Online (Sandbox Code Playgroud)
Jah*_*hid 12
覆盖意味着,给出具有相同参数的现有函数的不同定义,并且重载意味着添加具有不同参数的现有函数的不同定义.
例:
#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
}
Run Code Online (Sandbox Code Playgroud)
输出:
I am derived (overridden)
I am overloaded
Run Code Online (Sandbox Code Playgroud)
MER*_*MAS 11
1.Function Overloading是指类中存在多个具有相同名称的函数.函数重写是函数在基类和派生类中具有相同的原型.
2.Function重载可以在没有继承的情况下发生.函数重写发生在从另一个类继承一个类时.
3.过载的功能必须在参数数量上有所不同,或者参数类型应该不同.在重写中,函数参数必须相同.
有关更多详细信息,请访问以下链接,您可以在其中获得有关函数重载和覆盖的更多信息,请参阅c ++ https://googleweblight.com/i?u=https://www.geeksforgeeks.org/function-overloading-vs-function-重写型-CPP /&HL = EN-IN