题目描述
在多态概念中,基类的指针既可以指向基类的对象,又可以指向派生类的对象。我们可以使用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) {
int d = 0;
Shape* s = dynamic_cast<Shape*>(b);
if (s != 0)d= 0;
Triangle* t = dynamic_cast<Triangle*>(b);
if (t != 0)d=3;
Rectangle* r = dynamic_cast<Rectangle*>(b);
if (r != 0)d= 4;
return d;
}
int main() {
Shape s;
cout << getVertexCount(&s) << endl;
Triangle t;
cout << getVertexCount(&t) << endl;
Rectangle r;
cout << getVertexCount(&r) << endl;
}