【问题标题】:C++: Calling an Overload of pure virtual method in base from derived instanceC++:从派生实例调用基类中纯虚方法的重载
【发布时间】:2014-04-07 20:28:19
【问题描述】:

我有一个基类,它包含一个抽象方法func(int, float, unsigned) 和对此方法的重载func(int),以及一个实现抽象方法的派生类 .

class Base
{
public:
    virtual void func(int x, float y, unsigned z) = 0;

    void func(int x)
    {
        cout << "func with x only" << endl;
    }
};

class Derived : public Base
{
public:
    void func(int x, float y, unsigned z)
    {
        cout << "func override" << endl;
    }

};

在我的代码中,我有一个派生类的实例,它调用基类func(int) 的重载方法。

int main()
{
    Derived d;
    d.func(10);     // <<--------- 'COMPILATION ERROR'
    return 0;
}

在编译这段代码时,我得到以下编译错误:

error: no matching function for call to 'Derived::func(int&)'
note: candidates are: virtual void Derived::func(int, float, unsigned int)

这个错误的原因是什么/为什么这个代码不起作用?

【问题讨论】:

    标签: c++ inheritance g++ overriding overloading


    【解决方案1】:

    您需要将基类函数带入派生类的命名空间

    通过写作来做到这一点

    using Base::func;
    

    在你的子类的声明中。

    请注意,您是重载 func,而不是覆盖它。

    【讨论】:

    • 成功了,谢谢。我知道我正在“重载”函数而不是覆盖,我已经在问题中写了这个。但是,我不明白为什么没有 using 关键字就不能像基类中的其他方法一样工作
    • @user2758900 这是关于隐藏名称的。
    • @Bathsheba:也许吧。星期一讨论语义还为时过早,所以我将删除我的评论。
    • @MikeSeymour 我认为它应该是基类范围内的重载
    【解决方案2】:

    在 c++11 中:

    int main()
    {
        Base && b = Derived();
        b.func(10);    
        return 0;
    }
    

    【讨论】:

    • 这里的问题是从Derived 的对象调用Base::func,这意味着b 应该是Derived 类型。当类型为Derived 时,调用在编译时失败,因为在Derived 中实现的func 隐藏了存在于Base 中的名称func
    猜你喜欢
    • 2016-07-06
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2012-04-16
    相关资源
    最近更新 更多