【问题标题】:Unique instance of a commonly inherited base class共同继承的基类的唯一实例
【发布时间】:2012-02-17 10:49:04
【问题描述】:

我有以下类结构:

class Common {
//members and data here.
};

class Derived1 : public Common 
{
};

class Derived2: public Common, public Derived1
{
};

据我了解,Derived1Derived2 都将共享来自 Common 的任何成员。 有没有办法在Derived2 中将Derived1 设为私有以允许Derived2 仍然从Common 继承但具有单独的函数覆盖。 基本上我需要覆盖Derived1Derived2 中的一个虚函数,但仍然运行Derived1 的函数(它是一个线程API)。 任何帮助表示赞赏。

【问题讨论】:

  • 如果 Derived1 继承自 Common,而 Derived2 继承自 Derived1,为什么 Derived2 也继承自 Common?这不是多余的吗?
  • Common包含虚函数virtual void run()。如果您有一个 Common& 引用动态类型为 Derived2 的对象,并且您在该引用上调用 run(),您要调用哪个版本的覆盖函数?顺便说一句 - Derived1Derived2 不会共享一个 Common 对象。为了让他们共享单个 Common 基础对象,您必须在 Derived1Derived2 中虚拟地继承 Common

标签: c++ inheritance overriding multiple-inheritance


【解决方案1】:

正如@Walkerneo 指出的那样,您不需要同时继承Common 和Derived1。您可以简单地从 Derived1 继承,也可以从 Common 继承。您可以通过执行以下操作从 Derived2 的方法中显式调用 Derived1 的方法:

void Derived2::overriddenMethod ()
{
    // Do something unique here
    Derived1::overriddenMethod ();
    // Maybe do some more stuff
}

【讨论】:

    【解决方案2】:

    即使使用单一继承,您也可以实现这一点:

    struct Base
    {
        virtual void foo() = 0;
        virtual ~Base() { }
    };
    
    struct Intermediate : Base
    {
        virtual void foo() { /* ... */ }
        // ...
    };
    
    struct Derived : Intermediate
    {
        virtual void foo()
        {
            Intermediate::foo();
            // new stuff
        }
    };
    

    【讨论】:

      【解决方案3】:

      您是否尝试过为运行时多态性使用虚函数并将Derived2 类的变量分配给Derived1 类的指针

      class Common {
      //members and data here.
      public:
          virtual void commonFunction() = 0; //keeping it pure virtual
      };
      
      class Derived1 : public Common 
      {
          virtual void commonFunction(){
              //do something in derived1
          }
      };
      
      class Derived2: public Common, public Derived1
      {
          void commonFunction(){
              //do something in derived2
          }
      };
      int main(){
          Derived2 derived2;
          Derived1 *derived1;
          derived1 = &derived2;
          derived1->commonFunction(); //calls the common function definition in Derived1 
       /* ... */
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 1970-01-01
        • 2013-11-25
        • 1970-01-01
        • 1970-01-01
        • 2011-12-08
        相关资源
        最近更新 更多