覆盖具有相同名称的虚函数 [英] override virtual function with the same name

查看:79
本文介绍了覆盖具有相同名称的虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用相同的名称覆盖虚拟函数,如下所示:

I can override virtual function with the same name like this:

class I
{
public:
    virtual void foo() = 0;
};

class J
{
public:
    virtual void foo() = 0;
};

class C : public I, public J
{
public:
    virtual void I::foo() { cout << "I" << endl; }
    virtual void J::foo() { cout << "J" << endl; }
};


但是当我将两个函数移出类时,如下所示:


But when I move the two function out of the class,like this:

class C : public I, public J
{
public:
    virtual void I::foo();
    virtual void J::foo();
};
void C::I::foo() { cout << "I" << endl; }
void C::J::foo() { cout << "J" << endl; }


我遇到两个错误,说"foo"未在"C"中声明.


I got two error say ''foo'' not declared in ''C''.
Is there a way to implement the two functions out of the class?

推荐答案

不,您不能直接做到这一点.但是,有一些方法可以解决此限制.您必须引入一个中间步骤:

No, you can''t do it directly. There are ways around this limitation however. You would have to introduce an intermediate step:

//DECLARATION
class C : public I, public J
{
public:
    virtual void I::foo() { fooI(); }
    virtual void J::foo() { fooJ(); }

    void fooI();
    void fooJ();
};

//IMPLEMENTATION
void C::fooI() { cout << "I" << endl; }
void C::fooJ() { cout << "J" << endl; }



它不是很漂亮,但是AFAIK是完成您需要的最好方法.



It isn''t exactly pretty, but AFAIK it''s the best way to do what you need.


这篇关于覆盖具有相同名称的虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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