zoukankan      html  css  js  c++  java
  • 无代码 无说服力 4种 cast

         #include <iostream>

         using namespace std;

     

         class Base

         {

         public:

             int _base;

             virtual void printinfo()

             {

                  cout << _base << endl;

             }

         };

     

         class Derived : public Base

         {

         public:

             int _derived;

             virtual void printinfo()

             {

                  cout << _derived << endl;

             }

         };

     

         int main(void)

         {

             Base b1;

             Derived d1;

             int aInt = 10;

             long aLong = 11;

             float aFloat = 11.11f;

             double aDouble = 12.12;

     

             Derived* pd = static_cast<Derived*>(&b1);                       

       // down-casting          不安全

             Base* pb = static_cast<Base*>(&d1);                                 

     // up-casting                安全

             Derived& d = static_cast<Derived&>(b1);                            

    // down-casting          不安全

             Base& b = static_cast<Base&>(d1);                                     

    // up-casting                安全

     

             aInt = static_cast<int>(aFloat);                                               

    // 基本数据类型转换

             void* sth = static_cast<void*>(&aDouble);                         

      // double指针类型转换成void指针类型

             double* bDouble = static_cast<double*>(sth);                   

    // void指针类型转换成double指针类型

             cout << *bDouble << endl;c

     

             Base* pb1 = dynamic_cast<Base*>(&d1);

             //Derived* pd1 = dynamic_cast<Derived*>(&b1);                

    // 编译时有warning,运行时出错

     

             int bInt = reinterpret_cast<int>(pb1);                                      

    // 将地址或指针转换成整数

             cout << bInt << endl;

             pb1 = reinterpret_cast<Base*>(bInt);                                    

    // 将整数转换成地址或指针

     

             int* cInt = reinterpret_cast<int*>(&aFloat);                          

      // 这个转换的结果会出乎意料

             cout << (int)*cInt << endl;

     

             const Base* bBase = new Base();

             Base* cBase = const_cast<Base*>(bBase);

             //Base* dBase = dynamic_cast<Base*>(bBase);              

     // 不能通过编译

             //Base* eBase = static_cast<Base*>(bBase);                

        // 不能通过编译

             //Base* fBase = reinterpret_cast<Base*>(bBase);          

      // 不能通过编译

     

             return 0;

    }

  • 相关阅读:
    SqlServer2008启动不了的问题
    .exe 不包含适合入口点的静态“Main”方法
    两种常用的序列化
    异或运算^
    SqlServer数据库实现C#中的split功能
    遍历电脑下面所有文件--递归
    ExecuteNonQuery引发了System.ArgumentException类型异常
    JQuery属性过滤(转)
    SQL SERVER 执行远端数据库的SQL命令
    马云:做一个静静的观察者 能学到更多
  • 原文地址:https://www.cnblogs.com/titer1/p/2407936.html
Copyright © 2011-2022 走看看