c++ dynamic_cast

   在多态概念中,基类的指针既可以指向基类的对象,又可以指向派生类的对象。我们可以使用dynamic_cast类型转换操作符来判断当前指针(必须是多态类型)是否能够转换成为某个目的类型的指针。根据dynamic_cast的使用说明(如http://en.wikipedia.org/wiki/Run-time_type_information#dynamic_cast)

函数int getVertexCount(Shape * b)计算b的顶点数目,若b指向Shape类型,返回值为0;若b指向Triangle类型,返回值为3;若b指向Rectangle类型,返回值为4。


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;


class Shape{
public:
    Shape() {}
    virtual ~Shape() {}
};


class Triangle: public Shape{
public:
    Triangle() {}
    ~Triangle() {}
};


class Rectangle: public Shape {
public:
    Rectangle() {}
    ~Rectangle() {}
};


/*用dynamic_cast类型转换操作符完成该函数*/
int getVertexCount(Shape * b){
Triangle* t = dynamic_cast<Triangle*>(b);
Rectangle* r = dynamic_cast<Rectangle*>(b);

if (!t && !r)
  return 0;
if (t && !r)
  return 3;
if (!t && r)
  return 4;      

}


int main() {
    Shape s;
    cout << getVertexCount(&s) << endl;
    Triangle t;
    cout << getVertexCount(&t) << endl;
    Rectangle r;
    cout << getVertexCount(&r) << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值