[关闭]
@lupnfer 2017-03-01T07:16:20.000000Z 字数 1279 阅读 1093

std::dynamic_pointer_cast

Code Cpp


http://www.cplusplus.com/reference/memory/dynamic_pointer_cast/
这个demo是用dynamic_pointer_cast 来确保(派生-->基类)转换是OK的

下面是(派生-->基类)的逻辑
http://www.cnblogs.com/ider/archive/2011/08/01/cpp_cast_operator_part5.html

  1. #include <stdio.h>
  2. #include <memory>
  3. #include <string>
  4. #include <iostream>
  5. //class AA {
  6. //public:
  7. // //This makes CGpuResultBase a polymorphic type
  8. // virtual ~AA(){}
  9. //public:
  10. // static int type;
  11. //};
  12. //
  13. //class BB : public AA {
  14. //public:
  15. // int index;
  16. //};
  17. //
  18. //int AA::type = 4;
  19. struct AA {
  20. static int type;
  21. //This makes CGpuResultBase a polymorphic type
  22. virtual ~AA(){}
  23. };
  24. struct BB : AA {
  25. static int index;
  26. BB() {
  27. type = index;
  28. }
  29. };
  30. int AA::type = 1;
  31. int BB::index = 2;
  32. int fun(std::shared_ptr<AA> &p)
  33. {
  34. std::shared_ptr<BB> b(new BB());
  35. b->type = 1;
  36. std::cout <<"b:"<< b << std::endl;
  37. b->index = 3;
  38. p = std::dynamic_pointer_cast<AA>(b);
  39. }
  40. int main(int argc, char **argv)
  41. {
  42. std::shared_ptr<AA> p;
  43. std::shared_ptr<BB> b;
  44. std::cout <<"P:" << p << std::endl;
  45. fun(p);
  46. //std::cout <<"P:" << p << std::endl;
  47. std::cout << p->type << std::endl;
  48. b = std::dynamic_pointer_cast<BB> (p); //not safe but right
  49. std::cout << b->type << std::endl;
  50. std::cout << b->index << std::endl;
  51. }

各种cast

  1. const_cast <new_type> (expression) //移除 const跟volatile 属性
  2. static_cast <new_type> (expression) //不安全的类型装换
  3. reinterpret_cast <new_type> (expression)//指针跟整数互转
  4. dynamic_cast <new_type> (expression)//基类 派生类互转 基类必须有虚函数
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注