dau*_*ama 22 c++ oop overloading
我试图理解为什么下面的代码不能编译,显然该解决方案依赖于在派生类中明确声明对method_A的依赖.请参考以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
"test.cpp",(S)为"Derived :: method_A(int)"指定了错误的参数数量.
什么是阻止派生类知道其基类的技术原因是实现它试图重载的方法?我正在寻找更好地理解编译器/链接器在这种情况下的行为.
Dae*_*mon 37
它叫名字隐藏.当您定义一个与Base方法同名的非虚方法时,它会隐藏Derived类中的Base类方法,因此您将收到错误
myDerived.method_A(1,2);
Run Code Online (Sandbox Code Playgroud)
为了避免在Derived类中隐藏Base类方法,请像在Derived2类中一样使用关键字.
此外,如果你想让它工作,你可以明确地做到这一点
myDerived.Base::method_A(1,2);
Run Code Online (Sandbox Code Playgroud)
看看这个是为了更好地解释为什么隐藏名称隐藏起来.