C的类型准换
c类型转换:
隐式类型转换: 比如:double f = 1.0 / 2; 显示类型转换: (类型说明符)(表达式) 比如:double f = double(1) / double(2);
c类型转换的问题:
1.任意类型之间都可以转换,编译器无法判断起准确性 2.难于定位:在源码中无法快速定位
C++的类型转化
const_cast
用于转换指针或引用,去掉类型的const属性
int main(){//c++ const转换const int a = 10;int *pA = const_cast<int *>(&a);*pA = 100;return 0;}
reinterpret_cast
重新解释类型,既不检查指向的内容,也不检查指针类型本身;但要求转换前后的类型所占用内存大小一致,否则将引发编译时错误。
int Test(){cout << "reinterpret_cast test" <<endl;return 0;}int main(){//c++ reinterpret_cast转换typedef void(*FuncPtr)();FuncPtr funcPtr;// funcPtr = &Test;funcPtr = reinterpret_cast<FuncPtr>(&Test);funcPtr();return 0;}
static_cast
用于基本类型转换,有继承关系类对象和类指针之间转换,由程序员来确保转换是安全的,它不会产生动态转换的类型安全检查的开销;
int main(){//c++ static_cast转换int ii = 5;double d = static_cast<double >(ii);return 0;}
dynamic_cast
只能用于含有虚的数的类,必须用在多态体系中,用于类层次间的向上和向下转化;向下转化时,如果是非法的对于指针返回NULL;
#include <iostream>#include <string>using namespace std;class Base{public:Base() : _i(0) { ; }virtual void T() { cout << "Base:T" << _i << endl; }private:int _i;};class Derived : public Base{public:Derived() :_j(1) { ; }virtual void T() { cout << "Derived:T" << _j << endl; }private:int _j;};int main(){//dynamic_cast转换Base cb;Derived cd;Base* pcb;Derived* pcd;// 子类--》 父类pcb = static_cast<Base*>(&cd);if (pcb == NULL){cout << "unsafe static_cast from Derived to Base" << endl;}pcb = dynamic_cast<Base*>(&cd);if (pcb == NULL){cout << "unsafe dynamic_cast from Derived to Base" << endl;}// 父类--》 子类pcd = static_cast<Derived*>(&cb);if (pcd == NULL){cout << "unsafe static_cast from Base to Derived" << endl;}pcd = dynamic_cast<Derived*>(&cb);if (pcd== NULL){cout << "unsafe dynamic_cast from Base to Derived" << endl;}return 0;}
void*, NULL, nullptr
//◆在C语言中:#define NULL ((void *)0)//◆在C++语言中:#ifndef NULL#ifdef_ cplusplus#define NULL 0#else#define NULL ((void *)0)#endif//◆在C++11中,nullptr用来替代(void*)0, NULL则只表示0;
#include <iostream>#include <string>using namespace std;void func(void* i){cout << "func(void* i)" << endl;}void func(int i){cout << "func(int i)" << endl;}int main(){int* pi = NULL;int* pi2 = nullptr;char* pc = NULL;char* pc2 = nullptr;func(NULL); // func(int i)func(nullptr); // func(void* i)func(pi); // func(void* i)func(pi2); // func(void* i)func(pc); // func(void* i)func(pc2); // func(void* i)return 0;}
