在多態概念中,基類的指針既可以指向基類的對象,又可以指向派生類的對象。我們可以使用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。