overloading base class method in derived class(在派生类中重载基类方法)
问题描述
我试图理解为什么以下代码无法编译,显然该解决方案依赖于在派生类中专门声明对 method_A 的依赖.请参考以下代码:
I am trying to understand why the following code does not compile, apparently the solution relies in specifically declaring the dependency on method_A in the derived class. Please refer to the following code:
class Base
{
public:
void method_A(int param, int param2)
{
std::cout << "Base call A" << std::endl;
}
};
//does not compile
class Derived : public Base
{
public:
void method_A(int param)
{
std::cout << "Derived call A" << std::endl;
}
};
//compiles
class Derived2 : public Base
{
public:
using Base::method_A; //compile
void method_A(int param)
{
std::cout << "Derived call A" << std::endl;
}
};
int main ()
{
Derived myDerived;
myDerived.method_A(1);
myDerived.method_A(1,2);
Derived2 myDerived2;
myDerived2.method_A(1);
myDerived2.method_A(1,2);
return 0;
}
"test.cpp", (S) 为 "Derived::method_A(int)" 指定了错误数量的参数.
"test.cpp", (S) The wrong number of arguments have been specified for "Derived::method_A(int)".
阻止派生类知道其基类正在实现它试图重载的方法的技术原因是什么?我希望更好地理解编译器/链接器在这种情况下的行为.
What is the technical reason that prevents the derived class to know its base class is implementing the method it's trying to overload? I am looking in understanding better how the compiler/linker behaves in this case.
推荐答案
它叫做名称隐藏.当你定义一个与 Base 方法同名的非虚方法时,它会将 Base 类方法隐藏在派生类,因此您收到错误
Its called Name Hiding. When you define a non virtual method with the same name as Base method it hides the Base class method in Derived class so you are getting the error for
myDerived.method_A(1,2);
为了避免在派生类中隐藏基类类方法,请像在派生2类中那样使用关键字.
To avoid hiding of Base class methods in Derived class use using keyword as you did in Derived2 class.
另外,如果你想让它工作,你可以明确地做到
Also if you want to make it work you can do it explictly
myDerived.Base::method_A(1,2);
查看 this 以更好地解释为什么隐藏姓名.
Check out this for better explanation why name hiding came into picture.
这篇关于在派生类中重载基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在派生类中重载基类方法
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01