C++类型转换

C与C++类型转换

C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:

  TYPE b = (TYPE)a               

  
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用:

  • static_cast 静态类型转换。如int转换成char
  • reinterpreter_cast 重新解释类型
  • dynamic_cast 命名上理解是动态类型转换。如子类和父类之间的多态类型转换。用于类型识别
  • const_cast, 字面上理解就是去const属性
 1 #include <iostream>
 2 using namespace std;
 3 
 4 void printBuf(const char * p)
 5 {
 6     //p[0] = 'z';
 7     char *p1 = NULL;
 8 
 9     //获得的是地址
10     p1 = const_cast<char *>(p);   //风格4
11     p1[0] = 'Z';   //通过p1修改内存空间
12     cout << p << endl;
13 }
14 
15 class Tree {
16 
17 };
18 
19 class Animal
20 {
21 public:
22     virtual void cry() = 0;
23 
24 };
25 class Dog : public Animal
26 {
27 public:
28     virtual void cry()
29     {
30         cout << "汪汪汪" << endl;
31     }
32     void doHome()
33     {
34         cout << "看家" << endl;
35     }
36 };
37 
38 class Cat : public Animal
39 {
40 public:
41     virtual void cry()
42     {
43         cout << "喵喵喵" << endl;
44     }
45     void sajiao()
46     {
47         cout << "撒娇" << endl;
48     }
49 };
50 
51 void playObj(Animal * base)
52 {
53     base->cry();            //1有继承 2虚函数重写 3父类指针 指向子对象 ==》多态
54                             //能识别子类对象
55                             //风格3:dynamic_cast 运行时类型识别  RITT
56     Dog *pDog = dynamic_cast<Dog*>(base);   //父类对象转换为子类对象
57     if (pDog != NULL)                        //向下转型
58     {
59         pDog->doHome();
60     }
61     Cat *pCat = dynamic_cast<Cat *>(base);
62     if (pCat != NULL)
63     {
64         pCat->sajiao();
65     }
66 }
67 
68 int main()
69 {
70     double dpi = 3.1415269;
71     int ipi = (int)dpi;    // c语言强制类型转换
72     cout << ipi << endl;  
73 
74     //c++风格类型转换
75     int ipi2 = static_cast<int>(dpi); // 风格1:static_cast类型转换
76     cout << ipi2 << endl;
77 
78     Dog d1;
79     Cat c1;
80 
81     char * p1 = "12345";
82     int *p2 = NULL;
83     //p2 = static_cast<int*>(p1);       //不可以使用静态转换
84     p2 = reinterpret_cast<int *>(p1);//风格2:使用重新解释类型转换
85     cout << p2 << endl;        //输出p1的内存地址
86     Animal * pBase = NULL;
87     pBase = &d1;   //父类指针指向子类地址
88     pBase = static_cast<Animal *>(&d1);  //让C++编译在编译的时候进行 类型检查                                     //强制类型转换
89     pBase = reinterpret_cast <Animal *> (&d1);        //reinterpret_cast 强制类型转换
90      
91 }

 

原文地址:https://www.cnblogs.com/zmm1996/p/10533687.html