简体   繁体   English

C++子类继承

[英]C++ subclass inheritance

Ok, this might be silly question but I can't figure out how to fix my problem.好吧,这可能是个愚蠢的问题,但我不知道如何解决我的问题。

Let's assume we have 4 classes假设我们有 4 个类

  1. class A is a Base class A类是基类
  2. class B is derived from A with new methods (no override)类 B 派生自 A 并带有新方法(无覆盖)
  3. class C is derived from A类 C 派生自 A
  4. class D is derived from B (and also from A for inheritance)类 D 从 B 派生(也从 A 继承)

my question is: how do I use a method defined in B in D?我的问题是:如何使用 D 中 B 中定义的方法? If D inherit from BI get "error: member 'xxx' found in multiple base classes of different types" if D does not inherit from BI get "use of undeclared identifier"如果 D 从 BI 继承得到“错误:在不同类型的多个基类中找到成员 'xxx'” 如果 D 不是从 BI 继承得到“使用未声明的标识符”

Here's how it's done - based on your description:这是它的完成方式 - 根据您的描述:

class A {
protected:
    void foo();
};

class B : public A {
protected:
    void bar();
};

class D : public B {
protected:
    void baz() { B::bar(); }
};

Note that you should not have D inherit from A directly, except in very specific and rare cases.请注意,你应该有d继承A直接,除非是非常特殊和罕见的情况下。 Inheritance is transitive.继承是可传递的。

Also, next time, Please post a Minimal, Complete, and Verifiable example and don't make us guess what you mean exactly.另外,下次,请发布一个最小、完整和可验证的示例,不要让我们猜测您的确切含义。

In those cases in which the same method is available from the same subclasses from multiple inheritance paths are the "Diamond Pattern", and you can read about it here .在那些可以从多个继承路径的相同子类中使用相同方法的情况是“钻石模式”,您可以在此处阅读有关它的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM