【问题标题】:Multiple, but unique, class inheritance多个但唯一的类继承
【发布时间】:2018-04-27 19:54:46
【问题描述】:

问题是:ExampleIt 从类It 继承(并覆盖方法),所以当我在类Wrapped 中重载运算符时(它从It 调用一些方法,应该被@ 覆盖987654325@.

想要的效果是,当我重载operator* 时,我应该能够调用*name_of_Wrapped_class,这应该执行虚拟方法dereference(来自It),它应该被ExampleIt 覆盖。

class It {
public:
    virtual std::pair<int, std::string> dereference() const;
};

class ExampleIt : It {
public:
    std::pair<int, std::string> dereference() const override;
};

class Wrapped : It{ //??? not sure about that
public:
     std::pair<int, std::string> operator*() const; // it should call for dereference()
};

【问题讨论】:

  • 您的对象是否来自Wrapped ExampleIt?否则,我不确定你在问什么。也许您的意思是让Wrapped 继承自ExampleIt
  • 你的意思是Wrapped 应该持有一个指向It 的指针或引用,它可以引用从It 派生的任何类。?
  • 只是想创建一个调用虚函数的 shim 辅助函数吗?你可以在你的接口基类中声明这样的函数。
  • WrappedExampleIt 之间没有关系(除了它们碰巧都派生自 It)。任何一个的成员函数都不是另一个的成员函数。

标签: c++ c++11 operator-overloading virtual-functions


【解决方案1】:

在实际回答之前,我不得不说你的类层次结构和命名似乎有点可疑。您的解引用运算符返回一个值而不是引用 - 这不是解引用在普通指针上的工作方式。

不过,你要求它,所以你去吧。实现operator*() 重载的两个选项(每个选项都有其优点和缺点,我不会在这里讨论):

  1. 运行时多态行为,使用指针:

    class Wrapped {
    protected:
        It* it;
    public:
        std::pair<int, std::string> operator*() const {
            return it->dereference();
        };
    };
    
  2. 使用Curiously Recurring Template Pattern (CRTP)的编译时多态性:

    template <typename Base>
    class Wrapped: Base {
    public:
        std::pair<int, std::string> operator*() const {
            return Base::dereference();
        };
    };
    

    使用此选项,您甚至不需要 ItExampleIt 关联;任何具有dereference() 方法的类都可以。

【讨论】:

    【解决方案2】:

    这是示例代码,我认为它显示了您想要的,

          #include <iostream>
    
          using namespace std;
    
          class It {
          public:
              virtual std::pair<int, std::string> dereference() const{
                  std::cout << "it\n";
                  return make_pair(3, "");
              }
          };
    
          class ExampleIt : public It {
          public:
            std::pair<int, std::string> dereference() const override{
                  std::cout << "example it\n";
                  return make_pair(2, "");
              }
          };
    
          class Wrapped {
              It * it;
          public:
              Wrapped() : it (new ExampleIt()) {}
               std::pair<int, std::string> operator*() const{
                  std::cout << "Wrapped it\n";
                  it->dereference();
                  return make_pair(1, "");
               }
          };
    
          int main() {
              Wrapped p;
              auto x = *p;
              std::cout << x.first << std::endl;
          }
    

    注意成员it 在构造过程中被赋值为ExampleIt。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      相关资源
      最近更新 更多