能力查询

本文内容来源:《C++必知必会》条款27

能力查询用于判断一个对象是否支持一个特定的操作,它是通过对“不相关”的类型进行dynamic_cast转换而表达的,这种dynamic_cast用法通常被称为"cross-cast"。

1 #include <stdio.h>
2
3 class Rollable{
4 public:
5 virtual ~Rollable(){
6 }
7 virtual void roll() = 0;
8 };
9
10 class Shape{
11 public:
12 virtual ~Shape(){
13 }
14 virtual void draw() const = 0;
15 };
16
17 class Circle: public Shape, public Rollable{
18 public:
19 void draw() const {
20 printf("A circle is drawing!\r\n");
21 }
22 void roll(){
23 printf("A circle is rolling!\r\n");
24 }
25 };
26 class Square: public Shape{
27 public:
28 void draw() const{
29 printf(" A square is drawing!");
30 }
31 };
32 int main(int argc, char **argv)
33 {
34 Shape *pShape = new Circle();
35 pShape->draw();
36 Rollable *pRoller = dynamic_cast<Rollable *>(pShape);
37 if(pRoller){
38 //the Circle class has implemented the Rollable interface, thus pRoller is not NULL
39 pRoller->roll();
40 }
41 Shape *pShape2 = new Square();
42 pShape2->draw();
43 Rollable *pRoller2 = dynamic_cast<Rollable *>(pShape2);
44 if(pRoller2){
45 //the Square class hasn't implemented the Rollable interface,thus pRoller isNULL
46 pRoller2->roll();
47 }
48 return 0;
49 }

posted on 2011-05-25 17:01  Joshua Leung  阅读(248)  评论(0编辑  收藏  举报

导航