zoukankan      html  css  js  c++  java
  • Item 27. 能力质询(Capability Queries)

    Item 27. Capability Queries

    class Shape {
       public:
        virtual ~Shape();
        virtual void draw() const = 0;
        //...
    };
    class Rollable {
      public:
        virtual ~Rollable();
        virtual void roll() = 0;
    };

    class Circle : public Shape, public Rollable { // circles roll
        //...
        void draw() const;
        void roll();
        //...
    };
    class Square : public Shape { // squares don't
        //...
        void draw() const;
        //...
    };

    class Wheel : public Rollable { ... };

    上面的继承体系中,Circle采用的是多重继承。

    Shape *s = getSomeShape();

    现在我如何判断s能否执行roll呢?
    这就需要使用dynamic_cast操作符:
    Rollable *roller = dynamic_cast<Rollable *>(s);

    看起来挺奇怪:s明明是Shape ,怎么可以转换为与Shape毫不相干的Rollable?
    这就是Capability Queries:质询一个对象是否具有执行某个接口的能力。
    由于多态机制,假如s得到的是某个Circle 对象的指针,那么roller就能够得到该对象的指针,当然就可以使用Rollable 的方法:
    if(roller)
        roller->roll();
    这种使用dynamic_cast的方法,称为"cross-cast" ——交叉强制转换。

    不过,多重继承一直以来都不推荐使用,像java等语言根本就没有多重继承机制。
    当一个程序出现过多的cross-cast,那就要注意喽。

  • 相关阅读:
    LN : leetcode 283 Move Zeroes
    LN : Eden Polymorphic And OOP Design Pattern Abstract Factory
    LN : leetcode 242 Valid Anagram
    LN : leetcode 231 Power of Two
    LN : leetcode 191 Number of 1 Bits
    LN : leetcode 263 Ugly Number
    LN : leetcode 258 Add Digits
    LN : leetcode 292 Nim Game
    day5——Python整型、浮点型、布尔型及字符串
    day4——Python运算符
  • 原文地址:https://www.cnblogs.com/aiwz/p/6333225.html
Copyright © 2011-2022 走看看