【问题标题】:C++ design questionC++设计问题
【发布时间】:2009-12-20 23:31:31
【问题描述】:

假设我有一个类 Base,它有一个成员变量 A* my_hash。 我也有继承自类 Base 的扩展类。我也有B级 它扩展了 A。

class Base{
  Base(): my_hash(new A) {}
  //methods which use my_hash
protected:
  A* my_hash;

};

class Extended:public Base{
 //methods which use my_hash from A
 //I cannot have a B* my_other_hash in this class
 //I would like to substitute B* my_hash
 //I cannot let Base create my_hash (of type A*) because that is not what I want.
};

我希望 Extended 能像往常一样使用它(即使用它从 A 继承的所有东西),除了 并且有一个重要区别,我希望 my_hash 是 B* 而不是 A*。
每当有东西通过 Extended 的方法或 Base 的方法访问 my_hash 时, 我希望执行的方法是 B* 的。

要尝试的一件事: 我不能在扩展中重新定义方法调用(例如 Base() 中的 create_hash())。 这不起作用,因为在我创建哈希时似乎无法返回到扩展类。

我什至不想让 Base 知道 B。我该怎么做?

【问题讨论】:

  • B 是从 A 派生的吗?或者:B与A有什么关系吗?
  • @Federico:它在第一段中“我还有一个扩展 A 的 B 类。”
  • 通过下面的答案,确保类A中有虚方法,这样如果通过类A的指针调用该方法,就会执行B的方法。

标签: c++ inheritance oop constructor


【解决方案1】:

如果“B”的类型扩展了“A”,那么您可以设置它,以便通过构造函数传递“m_hash”的值(您也可以将此构造函数隐藏为受保护的代码,因此不会继承from 'Base' 不能扩展它)。

例如

class Base{
  Base(): my_hash(new A) {}
  //methods which use my_hash
protected:

  A* my_hash;
  Base(A* hash): my_hash(hash) {}
};

class Extended:public Base{
public:
  Extended() : Base(new B) {}
};

此外,如果您想在“B”中使用可以从“扩展”调用的新的专用函数,那么您可以将其存储在另一个指针中,或者只是将“my_hash”转换为“B*”类型。

【讨论】:

    【解决方案2】:

    您可以将 Base 类制作为 A 上的模板:

    template<typename T>
    class Base{
      Base(): my_hash(new T) {}
      //methods which use my_hash
    protected:
      T* my_hash;
    
    };
    
    class Extended:public Base<B>{
     ...
    };
    
    【解决方案3】:

    按照 Autopulated 的建议,模板可能是此处的方法。另一种方法实际上是有一个 B* my_other_hash (就像你在问题中提到的那样),然后在 B 的 ctor 中将 my_other_hash 设置为 my_hash。

    class Extended:public Base{
        ExtendedBase(): Base() {
            my_other_hash = my_hash;
        }
    }
    

    然后您可以访问 Base 中的 A 方法和 Extended 中的 A 或 B 方法。确保只删除其中一个!如果您在其他地方管理内存,则在 Base 的 dtor 或层次结构之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-21
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2017-09-24
      相关资源
      最近更新 更多