每个抽象类都知道其他人

时间:2017-06-16 23:51:17

标签: c++ inheritance abstract-class

我无法用文字清晰地表达我的想法。下面的例子可以解释我的想法。我有两个抽象类和两个Derived类,

class Base1{
        public:
        virtual void f1() = 0;
        std::string get(){ return "HelloWorld";}
};

class Derived1: public Base1{
        public:
        void f1() {}
        void update (std::string& update){
            **should call like**  Base2::Derived2::update_data(this);}
};

=>和

class Base2{
        public:
        virtual void f2 () = 0;
};

class Derived2: public Base2{
        public:
        void f2() {}
        void get (Base1& d1){ d1.Base1::get (); }
        void update_data (Base1& d1){ d1.Base1::get (); }
};

=>这些类被称为

int main(){
Derived1 d1;  
Derived2 d2;  

d2.get (d1);  
std::string hi = "hiWorld";
d1.update (hi);
return 0;
}

如何在**should call like**未传递Base2个实例的情况下实现d1.update ()

另一个问题是,当每个类对象知道其他对象时,它叫什么?

感谢。

1 个答案:

答案 0 :(得分:0)

您似乎需要一种名为double-dispatch的技术。 C++仅直接支持单一调度 - 您获得的行为仅基于单个实例。

   a->virtualFunction( params );  // exactly which implementation is called depends on the concrete type of a.

对于双重发送(不存在),您需要类似

的内容
  (a,b)->virtualFunction( params );  // where the call is based on both parameters.

这个问题有一些解决方案。这些需要工作,其中一种类型需要另一种类型的知识,但只是那种方式。

考虑一组我们想要在表面上绘制的几何形状。        class Surface;        class Drawable {          上市:             virtual~Srawable(){}             虚拟空白绘制(Surface *)= 0;        };

   class Surface {
     public:
        virtual ~Surface () {}
   // details ommitted.
   }

   class Rectangle : public Drawable {
   };
   class Circle : public Drawable {
   }

   // and some surfaces

   class PrinterSurface : public Surface {
   };

   class PlotterSurface : public Surface {
   };

我们实际想要调用的代码取决于表面和形状。

要解决这个问题,我们选择一个最有界的层次结构,并告诉另一个层次结构关于该类型的具体实例。

在这个例子中,人们认为存在比渲染它们的技术更多的形状和可绘制对象。

因此每个可绘制项目都知道如何在每个表面上绘制。

   class Drawable {
     public:
        virtual ~Drawable () {}
        virtual void drawPrinter( Surface * ) = 0;
        virtual void drawPlotter( Surface * ) = 0;
        virtual void drawSurface( Surface * ) = 0;
   };

   class Surface {
     public:
        virtual ~Surface () {}
        virtual void draw( Drawable * pDrawable ) = 0;
   }

   class PrinterSurface : public Surface { 
      void draw( Drawable * pDrawable ) {
           pDrawable->drawPrinter( this );
      }

   };

现在,对Surface->draw( Drawable *)的调用将被反弹到具体的实现中,其中每个Drawable都了解如何渲染到设备上,但设备不知道Drawable s的色域

如需进一步阅读:wikipedia : double dispatch以获得更完整的说明。

我会推荐设计模式书wikipedia : design patterns

设计模式提供了一些设计词汇的概念,这使得提出这种形式的问题变得更加容易。

相关问题