C ++纯虚方法 [英] C++ pure virtual methods

查看:372
本文介绍了C ++纯虚方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑此演示程序:

#include <stdio.h>

class Base
{
public:
    virtual int f(int) =0;
    virtual int f(){ return f(0); }

    virtual ~Base(){ }
};

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }
};

int main(void)
{
    Derived obj;
    printf("%d\n", obj.f(1));  // This works, and returns 11
    printf("%d\n", obj.f());   // Adding this line gives me the error listed below
}

编译错误:

virtualfunc.cpp: In function ‘int main()’:
virtualfunc.cpp:25:26: error: no matching function for call to ‘Derived::f()’
virtualfunc.cpp:15:9: note: candidate is: virtual int Derived::f(int)



我希望调用 obj.f()在调用 Base :: obj.f(),因为派生类没有定义它,这将导致调用 Derived :: obj.f(0)根据Base类中的定义。

My hope was that a call to obj.f() would result in a call to Base::obj.f() since the derived class doesn't define it, which would then result in a call to Derived::obj.f(0) per the definition in class Base.

我在这里做错了什么?有办法做到这一点吗?具体来说,我想调用 obj.f()返回10。

What am I doing wrong here? Is there a way to accomplish this? Specifically, I'd like the call to obj.f() to return 10.

我认为我可以使用默认参数来解决这个问题,但是这个代码只是一个简单的例子,所以请不要告诉我使用默认参数。)

(Also please note that I realize I could use a default argument to solve this, but this code is simply a concise example of my issue, so please don't tell me to use default arguments.)

感谢。

推荐答案

原因是定义的 f Derived hides f Base 类。解决方案是使用添加。像这样:

The reason is, that the defined f (in Derived ) hides the f functions from the Base class. The solution is to add using. Like this:

class Derived : public Base
{
public:
    int f(int i)
    {
        return (10 + i);
    }

//  vvvvvvvvvvvvvv
    using Base::f;
};

这篇关于C ++纯虚方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆