C的类型准换

c类型转换:

隐式类型转换: 比如:double f = 1.0 / 2; 显示类型转换: (类型说明符)(表达式) 比如:double f = double(1) / double(2);

c类型转换的问题:

1.任意类型之间都可以转换,编译器无法判断起准确性 2.难于定位:在源码中无法快速定位

C++的类型转化

const_cast

用于转换指针或引用,去掉类型的const属性

  1. int main(){
  2. //c++ const转换
  3. const int a = 10;
  4. int *pA = const_cast<int *>(&a);
  5. *pA = 100;
  6. return 0;
  7. }

reinterpret_cast

重新解释类型,既不检查指向的内容,也不检查指针类型本身;但要求转换前后的类型所占用内存大小一致,否则将引发编译时错误。

  1. int Test()
  2. {
  3. cout << "reinterpret_cast test" <<endl;
  4. return 0;
  5. }
  6. int main(){
  7. //c++ reinterpret_cast转换
  8. typedef void(*FuncPtr)();
  9. FuncPtr funcPtr;
  10. // funcPtr = &Test;
  11. funcPtr = reinterpret_cast<FuncPtr>(&Test);
  12. funcPtr();
  13. return 0;
  14. }

static_cast

用于基本类型转换,有继承关系类对象和类指针之间转换,由程序员来确保转换是安全的,它不会产生动态转换的类型安全检查的开销;

  1. int main(){
  2. //c++ static_cast转换
  3. int ii = 5;
  4. double d = static_cast<double >(ii);
  5. return 0;
  6. }

dynamic_cast

只能用于含有虚的数的类,必须用在多态体系中,用于类层次间的向上和向下转化;向下转化时,如果是非法的对于指针返回NULL;

  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. Base() : _i(0) { ; }
  8. virtual void T() { cout << "Base:T" << _i << endl; }
  9. private:
  10. int _i;
  11. };
  12. class Derived : public Base
  13. {
  14. public:
  15. Derived() :_j(1) { ; }
  16. virtual void T() { cout << "Derived:T" << _j << endl; }
  17. private:
  18. int _j;
  19. };
  20. int main(){
  21. //dynamic_cast转换
  22. Base cb;
  23. Derived cd;
  24. Base* pcb;
  25. Derived* pcd;
  26. // 子类--》 父类
  27. pcb = static_cast<Base*>(&cd);
  28. if (pcb == NULL)
  29. {
  30. cout << "unsafe static_cast from Derived to Base" << endl;
  31. }
  32. pcb = dynamic_cast<Base*>(&cd);
  33. if (pcb == NULL)
  34. {
  35. cout << "unsafe dynamic_cast from Derived to Base" << endl;
  36. }
  37. // 父类--》 子类
  38. pcd = static_cast<Derived*>(&cb);
  39. if (pcd == NULL)
  40. {
  41. cout << "unsafe static_cast from Base to Derived" << endl;
  42. }
  43. pcd = dynamic_cast<Derived*>(&cb);
  44. if (pcd== NULL)
  45. {
  46. cout << "unsafe dynamic_cast from Base to Derived" << endl;
  47. }
  48. return 0;
  49. }

void*, NULL, nullptr

  1. //◆在C语言中:
  2. #define NULL ((void *)0)
  3. //◆在C++语言中:
  4. #ifndef NULL
  5. #ifdef_ cplusplus
  6. #define NULL 0
  7. #else
  8. #define NULL ((void *)0)
  9. #endif
  10. //◆在C++11中,nullptr用来替代(void*)0, NULL则只表示0;
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. void func(void* i)
  5. {
  6. cout << "func(void* i)" << endl;
  7. }
  8. void func(int i)
  9. {
  10. cout << "func(int i)" << endl;
  11. }
  12. int main()
  13. {
  14. int* pi = NULL;
  15. int* pi2 = nullptr;
  16. char* pc = NULL;
  17. char* pc2 = nullptr;
  18. func(NULL); // func(int i)
  19. func(nullptr); // func(void* i)
  20. func(pi); // func(void* i)
  21. func(pi2); // func(void* i)
  22. func(pc); // func(void* i)
  23. func(pc2); // func(void* i)
  24. return 0;
  25. }