C++ dynamic_cast对指针类型的转换

C8-3 三角形还是长方形?

(100.0/100 points)
题目描述

在多态概念中,基类的指针既可以指向基类的对象,又可以指向派生类的对象。我们可以使用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。


 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 class Shape{
 7 public:
 8     Shape() {}
 9     virtual ~Shape() {}
10 };
11 
12 class Triangle : public Shape{
13 public:
14     Triangle() {}
15     ~Triangle() {}
16 };
17 
18 class Rectangle : public Shape {
19 public:
20     Rectangle() {}
21     ~Rectangle() {}
22 };
23 
24 /*用dynamic_cast类型转换操作符完成该函数*/
25 int getVertexCount(Shape * b){
26     Rectangle* rectangle = dynamic_cast<Rectangle*>(b);
27     if (rectangle != nullptr)
28         return 4;
29     Triangle* triangle = dynamic_cast<Triangle*>(b);
30     if (triangle != nullptr)
31         return 3;
32     return 0;
33 }
34 
35 int main() {
36     Shape s;
37     cout << getVertexCount(&s) << endl;
38     Triangle t;
39     cout << getVertexCount(&t) << endl;
40     Rectangle r;
41     cout << getVertexCount(&r) << endl;
42 }

查阅Wikipedia,对照例子不难AC。

原文地址:https://www.cnblogs.com/maples7/p/4520756.html