C++ dynamic_cast对指针类型的转换
2015-05-21 20:52
274 查看
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。
#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){ Rectangle* rectangle = dynamic_cast<Rectangle*>(b); if (rectangle != nullptr) return 4; Triangle* triangle = dynamic_cast<Triangle*>(b); if (triangle != nullptr) return 3; return 0; } int main() { Shape s; cout << getVertexCount(&s) << endl; Triangle t; cout << getVertexCount(&t) << endl; Rectangle r; cout << getVertexCount(&r) << endl; }
查阅Wikipedia,对照例子不难AC。
相关文章推荐
- 深入理解 C++ 指针(八)---指针类型转换
- Swift中如何转换不同类型的Mutable指针
- c++ dynamic_cast 转换详解
- 【转】使用标准C++的类型转换符:static_cast、dynamic_cast、const_cast和reinterpret_cast
- C++中的四种显式类型转换之const_cast、reinterpret
- 关于c++ 强制转换类型运算符 static_cast、dynamic_cast、reinterpret_和const_cast
- 标准C++的类型转换符:static_cast、dynamic_cast、reinterpret_cast和const_cast(转载)
- C语言指针转换为intptr_t类型
- 指针类型转换后, 指针值会改变
- 从“void*”到指向非“void”的指针的转换要求显式类型转换错误
- C++ 类型转换 (static_cast dynamic_cast reinterpret_cast const_cast typeid)
- 类型转换操作符static_cast, dynamic_cast 以及 reinterpret_cast
- 关于Spring事务代理类型转换问题($ProxyXX cannot be cast to 类型)(一)
- 4种类型转换操作符 (static_cast const_cast dynamic_cast reinterpret_cast)
- 解决spring使用动态代理类型转换失败的问题--java.lang.ClassCastException: com.sun.proxy.$Proxy$ cannot be cast to ...今天
- static_cast、dynamic_cast、reinterpret_cast和const_cast 类型转换
- 从零开始学C++之从C到C++(二):引用、数组引用与指针引用、内联函数inline、四种类型转换运算符
- C++中的类型转换(static_cast,dynamic_cast,const_cast,reinterpret_cast)
- c++ 类型转换整理一:static_cas t和 reinterpret_cast
- 关于指针强制类型转换的思考