【发布时间】:2013-05-30 12:15:45
【问题描述】:
我试图理解为什么以下代码无法编译,显然解决方案依赖于在派生类中明确声明对 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;
}
"test.cpp", (S) 为 "Derived::method_A(int)" 指定了错误数量的参数。
阻止派生类知道其基类正在实现它试图重载的方法的技术原因是什么? 我希望更好地了解编译器/链接器在这种情况下的行为方式。
【问题讨论】:
-
你错过了
virtual吗? -
不,我的意图是重载函数。如果我们没有对象继承,它会像: void method_A(int param, int param2); void method_A(int param);
标签: c++ oop overloading