您的位置:首页 > 其它

能力查询

2011-05-25 17:01 288 查看
本文内容来源:《C++必知必会》条款27

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

#include <stdio.h>

class Rollable{
public:
virtual ~Rollable(){
}
virtual void roll() = 0;
};

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

class Circle: public Shape, public Rollable{
public:
void draw() const {
printf("A circle is drawing!\r\n");
}
void roll(){
printf("A circle is rolling!\r\n");
}
};
class Square: public Shape{
public:
void draw() const{
printf(" A square is drawing!");
}
};
int main(int argc, char **argv)
{
Shape *pShape = new Circle();
pShape->draw();
Rollable *pRoller = dynamic_cast<Rollable *>(pShape);
if(pRoller){
//the Circle class has implemented the Rollable interface, thus pRoller is not NULL
pRoller->roll();
}
Shape *pShape2 = new Square();
pShape2->draw();
Rollable *pRoller2 = dynamic_cast<Rollable *>(pShape2);
if(pRoller2){
//the Square class hasn't implemented the Rollable interface,thus pRoller isNULL
pRoller2->roll();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: