我对这两个术语有点困惑,很高兴能澄清一些疑问。
据我了解 函数重载
意味着在同一个类中具有多个具有相同名称但具有不同数量的参数、不同类型的参数或参数序列的方法,而与没有返回类型的返回类型无关影响函数名称的错位。
上述定义是否还包括“....在同一个类中或跨相关类(通过继承相关).....”
而Function Overriding
与虚函数相关,相同的方法签名(在基类中声明为virtual)并在子类中被重写。
我想知道一个场景,下面是代码:
#include <iostream>
class A
{
public:
void doSomething(int i, int j)
{
cout<<"\nInside A::doSomething\n";
}
};
class B: public A
{
public:
void doSomething(int i, int j)
{
cout<<"\nInside B::doSomething\n";
}
};
int main()
{
B obj;
obj.doSomething(1,2);
return 0;
}
在上面的场景中,可以说:
派生类中的方法 overrides
基类中的方法 OR
派生类中的方法 重载
基类中的方法
重载是否适用于类范围,是否覆盖术语不一定适用于虚函数?
我认为它应该是 overrides
,但只需要澄清一下,因为我碰巧记得术语覆盖专门用于虚函数。
最佳答案
- 隐藏是指由于嵌套范围或派生类 (3.3.7/1) 中的声明而无法访问范围中的定义。
A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class.
- 覆盖是指派生类中的虚拟成员被替换(参见 10.3/2)
If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual an it overrides Base::vf.
- 重载是指多个声明在同一范围内共存同名 (13/1)
When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded.
- 相关,也有可能将 operator new 和 delete 从标准库中替换为自己的实现(18.4.1.1/2、18.4.1.1/6、18.4.1.1/11、18.4.1.2)
所以这显然是一个隐藏的情况。
关于c++ - 重载与覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406533/