以下是对C++中overload,override,overwrite的区别进行了详细的分析介绍,需要的朋友可以过来参考下
Overload(重载):在C++程序中,可以将语义、功能相似的几个函数用同一个名字表示,但参数或返回值不同(包括类型、顺序不同),即函数重载。
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual 关键字可有可无。
Override(覆盖):是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual 关键字。
Overwrite(重写):是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)。
走过路过不要错过 下面才是重点:
上面是截取的度娘 某c论坛的部分说明
overload+override是比较常见的,就不多说了,
针对overwirte,我写了如下例子,外加调试,发现根本就不是这样的
// =======================================================================================
// over()
// show override overload overwrite
class mybase {
public:
mybase () {
}
virtual ~mybase () {
}
virtual void dosomething ( int i ) {
std::cout << "dosomething ( int i )" << i << std::endl;
}
virtual void dosomething ( std::string s ) {
std::cout << "dosomething ( std::string s )" << s << std::endl;
}
void dosomething ( std::vector<int>& v ) {
for ( auto x : v )
std::cout << "b - " << x << std::endl;
}
};
class myderive : public mybase {
public:
myderive () {
}
~myderive () {
}
void dosomething ( std::string s ) {
std::cout << "dosomething ( std::string s ) _ derive " << s << std::endl;
}
void dosomething ( std::vector<int>& v ) {
for ( auto x : v )
std::cout << "v - " << x << std::endl;
}
};
void over () {
mybase* p = new myderive ();
p->dosomething ( "hello" );
p->dosomething ( 123 );
std::vector<int> v = { 1, 2, 3 };
p->dosomething ( v );
delete p;
p = nullptr;
}
// =======================================================================================
说好的隐藏呢 在哪呢,最后不得已 上google搜索了c++ overwrite,发现根本就没有相关的解释,最后在stackoverflow找到了两个比较靠谱的说法:
In C++ terminology, you have overriding (relating to virtual methods in a class hierarchy) and overloading (related to a function having the same name but taking different parameters). You also have hiding of names (via explicit declaration of the same name in a nested declarative region or scope).
The C++ standard does not use the term “overwrite” except in its canonical English form (that is, to replace one value with a new value, as in the assignment x = 10 which overwrites the previous value of x).
第二个是:
The usual distinction I’m familiar with is of overriding and overloading. Virtual functions are overridden. Functions are overloaded when there’s a version with same name but different signature (this exists in many languages). In C++ you can also overload operators.
AFAIK, overwriting is an unrelated concept (overwrite a variable, file, buffer, etc.), and is not specific to C++ or even OOP languages.
总结:overwirte不是c++的术语也不是c++的概念。
在读本文之前 你真的分得清黑人中的奥巴马、尼古拉斯凯奇、成龙吗