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.
这篇关于在派生类中重载基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在派生类中重载基类方法
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
