这里先有一个问题:
问题描述:函数int getVertexCount(Shape * b)计算b的顶点数目,若b指向Shape类型,返回值为0;若b指向Triangle类型,返回值为3;若b指向Rectangle类型,返回值为4。
其中,Triangle和Rectangle均继承于Shape类。
此问题的主函数已规定如下:
int main() {
Shape s;
cout << getVertexCount(&s) << endl;
Triangle t;
cout << getVertexCount(&t) << endl;
Rectangle r;
cout << getVertexCount(&r) << endl;
}
分析:首先,问题要求的即类似与Java和C#中的反射机制,这里我们考虑使用dynamic_cast函数,关于用法,我们先看一段函数:
//A is B‘s father
void my_function(A* my_a)
{
B* my_b = dynamic_cast<B*>(my_a);
if (my_b != nullptr)
my_b->methodSpecificToB();
else
std::cerr << " Object is not B type" << std::endl;
}
只要对对象指针是否是nullptr即可判断该对象运行是是哪个类的对象,全部代码如下:
#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类型转换操作符完成该函数计算b的顶点数目,若b指向Shape类型,返回值为0;若b指向Triangle类型,返回值为3;若b指向Rectangle类型,返回值为4。*/
int getVertexCount(Shape * b){
Triangle* my_triangle = dynamic_cast<Triangle*>(b);
if (my_triangle != nullptr)
{
//说明是Triangle
return 3;
}
Rectangle* my_Rectangle = dynamic_cast<Rectangle*>(b);
if (my_Rectangle != nullptr)
{
//说明是Rectangle
return 4;
}
return 0;
}
int main() {
Shape s;
cout << getVertexCount(&s) << endl;
Triangle t;
cout << getVertexCount(&t) << endl;
Rectangle r;
cout << getVertexCount(&r) << endl;
}
原文:http://www.cnblogs.com/AvalonRookie/p/7134383.html