@lupnfer
        
        2017-03-01T07:16:20.000000Z
        字数 1279
        阅读 1184
    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
#include <stdio.h>#include <memory>#include <string>#include <iostream>//class AA {//public:// //This makes CGpuResultBase a polymorphic type// virtual ~AA(){}//public:// static int type;//};////class BB : public AA {//public:// int index;//};////int AA::type = 4;struct AA {static int type;//This makes CGpuResultBase a polymorphic typevirtual ~AA(){}};struct BB : AA {static int index;BB() {type = index;}};int AA::type = 1;int BB::index = 2;int fun(std::shared_ptr<AA> &p){std::shared_ptr<BB> b(new BB());b->type = 1;std::cout <<"b:"<< b << std::endl;b->index = 3;p = std::dynamic_pointer_cast<AA>(b);}int main(int argc, char **argv){std::shared_ptr<AA> p;std::shared_ptr<BB> b;std::cout <<"P:" << p << std::endl;fun(p);//std::cout <<"P:" << p << std::endl;std::cout << p->type << std::endl;b = std::dynamic_pointer_cast<BB> (p); //not safe but rightstd::cout << b->type << std::endl;std::cout << b->index << std::endl;}
const_cast <new_type> (expression) //移除 const跟volatile 属性static_cast <new_type> (expression) //不安全的类型装换reinterpret_cast <new_type> (expression)//指针跟整数互转dynamic_cast <new_type> (expression)//基类 派生类互转 基类必须有虚函数