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.
这篇关于在派生类中重载基类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在派生类中重载基类方法
				
        
 
            
        基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				