无法调用基类函数

时间:2015-06-09 04:22:56

标签: c++ inheritance

我不明白为什么这段代码会出现编译错误,这不是覆盖的情况,因为base和child类中的参数列表不同,所以任何人都可以帮助我。

#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;
}

3 个答案:

答案 0 :(得分:4)

在查找匹配函数时,编译器会连续搜索更大的范围,直到找到包含正确名称的范围。然后(对于函数调用)它将该范围内的所有内容与该名称一起收集,并对它们进行重载解析以找到要调用的正确对象。如果它们都不能被调用,它就会停止,并且它是一个错误。它继续搜索更多范围,寻找另一个要调用的函数。

为了使工作正常,您可以将基类函数的名称带入派生类的范围:

class Derived : public Base
{
    public:
    using Base::func;   // <--- this is what we added
    void func ( int inVal) 
    { 
        cout<< b <<"-> "<<inVal;
    }

    protected:
    int b;
 };

有了这个,编译器会将Derived::funcBase::func视为重载集,并且看到您没有传递任何参数,因此Base::func是唯一的参数你可以打电话,这就是它解决的问题。

答案 1 :(得分:1)

func中的Drived隐藏了Base中的d.Base::func(); 。调用它的最简单方法是指定范围:

Base::func

如果Base是虚函数,则会禁用虚拟调度。另一种解决方案是使用 using-declaration Drived声明引入class Drived : public Base { public: using Base::func; void func(int inVal) ... }; 类范围:

{{1}}

答案 2 :(得分:0)

粘贴此行,它将起作用

Drived d;
d.func(1); //whats changed?
return 0;
return 0;

我相信你应该自己找出差异。它并不难。看看