我不明白为什么这段代码会出现编译错误,这不是覆盖的情况,因为基类和子类中的参数列表不同,所以谁能帮我解决这个问题。
#include <iostream>
using namespace std;
class Base
{
public:
void func ( )
{
cout<< a ;
}
protected:
int a;
};
class Drived : public Base
{
public:
void func ( int inVal)
{
cout<< b <<"-> "<<inVal;
}
protected:
int b;
};
int main(int argc, char* argv[])
{
Drived d;
d.func(); //->Compilation error why and how can we avoid it?
return 0;
}
最佳答案
在查找匹配函数时,编译器会依次搜索更大的作用域,直到找到包含正确名称的作用域。然后(对于函数调用)它收集该范围内具有该名称的所有内容,并对它们进行重载解析以找到正确的调用。如果它们都不能被调用,它就会停止,这是一个错误。它不会继续搜索更多范围以寻找要调用的另一个函数。
要使事情正常进行,您可以将基类函数的名称放入派生类的范围内:
class Derived : public Base
{
public:
using Base::func; // <--- this is what we added
void func ( int inVal)
{
cout<< b <<"-> "<<inVal;
}
protected:
int b;
};
有了它,编译器会将 Derived::func
和 Base::func
视为重载集,并看到您没有传递任何参数所以 Base::func
是您唯一可以调用的,所以这就是它解析的结果。
关于c++ - 无法调用基类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30722976/