43.c++指针类型转换


  • 数据类型转换(static_cast)
    //数据类型转换
    printf("%d\n", static_cast<int>(10.2));

     

  • 指针类型转换(reinterpret_cast)
    1 指针类型转换
    2 int *pint = new int(1);
    3 char *pch = reinterpret_cast<char *>(pint);

     

  • 涉及到const的指针类型转换(const_cast)
    1 const int num[5] = { 1,2,3,4,5 };
    2 const int *p = num;
    3 int *pint = const_cast<int *>(p);

     

     

  • 子类转化为父类(dynamic_cast)
     1 class man
     2 {
     3 public:
     4     int name;
     5     //加上virtual关键字,可以使得父类用子类初始化后可以调用子类的函数
     6     virtual void run()
     7     {
     8         cout << "man is running" << endl;
     9     }
    10 };
    11 
    12 class son :public man
    13 {
    14 public:
    15     void run()
    16     {
    17         cout << "son is running" << endl;
    18     }
    19 };
    20 
    21 void main()
    22 {
    23     /*man man1;
    24     son son1;
    25     man *p = &man1;
    26     p->run();
    27     p = &son1;
    28     p->run();*/
    29     man *pman = new man;
    30     son *pson = new son;
    31     //子类指针转换为父类指针,但是还是调用子类的函数
    32     man *pfu = dynamic_cast<man *>(pson);
    33     pfu->run();
    34     system("pause");
    35 }

     


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM