多个基类可以有相同的虚方法吗? [英] Can multiple base classes have the same virtual method?

查看:34
本文介绍了多个基类可以有相同的虚方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. A 类有一个纯虚方法 read()
  2. B 类有一个实现的虚方法 read()
  3. 我有一个继承A和B的C类
  4. 这会发生吗?

我想要实现的是两个基类 A 和 B 相互补充.

What I'm trying to achieve is that the two base classes A and B complement each other.

所以 C read() 方法实际上会调用类 B read()

So C read() method would actually call class B read()

class A {
    virtual int get_data() = 0;

    void print() {
        log(get_data());
    }
}

class B {
    virtual int get_data() {
        return 4;
    }
}

class C : public A, public B {

}

C my_class;
my_class.print(); // should log 4;

我不在我的电脑上,也不会在接下来的几周内有机会,所以我无法测试这个......但我正在设计架构,需要知道这是否可行,如果不可行......这怎么可能!

I'm not on my computer nor will have opportunity in the next couple of weeks so I can't test this... but I'm designing the architecture and needed to know if this is possible and if not.. how can this be accomplished!

推荐答案

多个基类可以有相同的虚方法吗?

Can multiple base classes have the same virtual method?

  1. 这会发生吗?

是的.

所以 C read() 方法实际上会调用 B 类 read()

So C read() method would actually call class B read()

这不会自动发生.base 的成员函数不会覆盖无关基的函数.

That doesn't happen automatically. A member function of base doesn't override a function of an unrelated base.

您可以向 C 添加覆盖:

You can add an override to C:

class C : public A, public B {
    int get_data() override;
}

这会覆盖A::get_dataB::get_data.为了实际调用B类read()",你确实可以进行这样的调用:

This overrides both A::get_data and B::get_data. In order to "actually call class B read()", you can indeed make such call:

int C::get_data() {
    return B::get_data();
}

或者...如果您没有将 B::get_data 声明为私有,那也是可能的.

Or... that would be possible if you hadn't declared B::get_data private.

如果您稍微更改层次结构,则可以在不显式委派派生的中覆盖另一个基础中的函数.特别是,您需要一个公共基础和虚拟继承:

Overriding a function in another base without explicitly delegating in derived is possible if you change your hierarchy a bit. In particular, you need a common base, and virtual inheritance:

struct Base {
    virtual int get_data() = 0;
};

struct A : virtual Base {
    void print() {
        std::cout << get_data();
    }
};

struct B : virtual Base {
    int get_data() override {
        return 4;
    }
};

struct C : A, B {};

这篇关于多个基类可以有相同的虚方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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