Item 27. Capability queries

xiaoxiao2021-03-05  23

Item 27. Capability queries

Class shape {public: virtual ~ shape (); virtual void draw () const = 0; //... };class rollable {public: virtual ~ roll (); virtual void roll () = 0;};

Class Circle: Public Shape, Public Rollable {// Circles Roll // ... Void Draw () const; void (); //...} etcface square: public shape {// Squares don't // ... void Draw () const; // ...};

Class Wheel: Public ROLLABLE {...};

In the above inheritance system, Circle uses multiple inheritance.

Shape * s = getsomeshape ();

Now how do I determine whether S can execute ROLL? This requires using the Dynamic_cast operator: ROLLABLE * ROLLER = DYNAMIC_CAST (S);

It looks quite strange: S is obviously Shape, how can I convert to the rollable that is unhappy with Shape? This is the Capability Queries: Question No Obility has the ability to perform an interface. Due to the polymorphic mechanism, if S gets a pointer to a Circle object, the Roller can get the pointer of the object, of course, the method of Rollable can be used: if (roller) roller-> roll (); this use Dynamic_CAST Method, called "Cross-Cast" - crossforced conversion.

However, multiple inherits have always been recommended, and there is no multiple inheritance mechanisms like Java. When a program has excessive Cross-Cast, then pay attention to.

转载请注明原文地址:https://www.9cbs.com/read-35683.html

New Post(0)