加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C从具有相同虚函数名称的多个基类继承

发布时间:2020-12-16 09:10:03 所属栏目:百科 来源:网络整理
导读:我试过这段代码: class A{ virtual void foo() = 0;};class B{ virtual void foo() = 0;};class C : public A,public B{ //virtual void A::foo(){} //virtual void B::foo(){} virtual void A::foo(); virtual void B::foo();};void C::A::foo(){}void C::
我试过这段代码:

class A
{
    virtual void foo() = 0;
};

class B
{
    virtual void foo() = 0;
};

class C : public A,public B
{
    //virtual void A::foo(){}
    //virtual void B::foo(){}

    virtual void A::foo();
    virtual void B::foo();
};

void C::A::foo(){}
void C::B::foo(){}

int main()
{
    C c;
    return 0;
}

使用注释部分时可以,但是当我尝试在类声明之外编写定义时,编译器会报告错误.
我正在使用MSVC11编译器,有谁知道怎么写这个?
我需要将代码移动到cpp文件中.

谢谢~~

解决方法

函数根据名称和参数类型覆盖基类的虚函数(参见下文).因此,你的类C有两个虚函数foo,一个从每个A和B继承.但函数void C :: foo()会覆盖两个:

[class.virtual] / 2

If a virtual member function vf is declared in a class Base and in a class Derived,derived directly or indirectly from Base,a member function vf with the same name,parameter-type-list,cv-qualification,and ref-qualifier (or absence of same) as Base::vf is declared,then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

正如我在评论中已经说过的那样,[dcl.meaning] / 1禁止在(成员)函数的声明中使用qualified-id:

When the declarator-id is qualified,the declaration shall refer to a previously declared member of the class or namespace to which the qualifier refers […]”

因此任何虚拟的空虚X :: foo();作为C内部的声明是非法的.

代码

class C : public A,public B
{
    virtual void foo();
};

是AFAIK覆盖foo的唯一方法,它将覆盖A :: foo和B :: foo.对于A :: foo和B :: foo,除了引入另一个继承层之外,没有办法对其进行两种不同的覆盖:

#include <iostream>

struct A
{
    virtual void foo() = 0;
};

struct B
{
    virtual void foo() = 0;
};

struct CA : A
{
    virtual void foo() { std::cout << "A" << std::endl; }
};

struct CB : B
{
    virtual void foo() { std::cout << "B" << std::endl; }
};

struct C : CA,CB {};

int main() {
    C c;
    //c.foo();  // ambiguous

    A& a = c;
    a.foo();

    B& b = c;
    b.foo();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读