1)static_cast<>() 静态类型转换,编译的时c++编译器会做类型检查;基本类型能转换 但是不能转换指针类型
2)若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
3)一般性结论:
C语言中 能隐式类型转换的,在c++中可用 static_cast<>()进行类型转换。因C++编译器在编译检查一般都能通过;
C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释。总结:static_cast<>()和reinterpret_cast<>() 基本上把C语言中的 强制类型转换给覆盖
reinterpret_cast<>()很难保证移植性。
4)dynamic_cast<>(),动态类型转换,安全的基类和子类之间转换;运行时类型检查
5)const_cast<>(),去除变量的只读属性
实例:
#include <iostream>
using namespace std;
class Tree
{
};
class Animal
{
public:
virtual void cry() = 0;
};
class Dog :public Animal
{
public:
virtual void cry()
{
cout << "汪汪" << endl;
}
void doHome()
{
cout << "看家" << endl;
}
};
class Cat :public Animal
{
private:
virtual void cry()
{
cout << "喵喵" << endl;
}
public:
void dothing()
{
cout << "抓老鼠" << endl;
}
};
void print(const char * p)
{
//p[0] = 'H'; //报错,不能修改,因为p是常量指针,其内存空间不能修改
char *base = NULL;
base = const_cast<char*>(p);
base[0] = 'H';
cout << p << endl;
}
void main()
{
char p[] = "huangxiangao";
char *p1 = "huangxiangao";
print(p); //正常修改
//print(p1); //产生中断,因为p1是常量,没有内存空间,根本不能修改
system("pause");
}
void playObj(Animal *base)
{
base->cry(); //发生多态 继承,虚函数重写,父类指针指向子类指针
Dog *dogp = dynamic_cast<Dog *>(base);
if (dogp != NULL)
{
dogp->doHome();
}
Cat *catp = dynamic_cast<Cat *>(base); //运行时动态判断类型,主要用于父子类之间
if (catp != NULL)
{
catp->dothing();
}
}
void main02()
{
Dog d1;
Cat c1;
playObj(&d1);
playObj(&c1);
Tree t1;
Animal * base = NULL;
//base = static_cast<Animal *>(&t1); //出错
base = reinterpret_cast<Animal *>(&t1);//编译通过
system("pause");
}
void main01()
{
int a = 10;
char b = 'c';
a = static_cast<int>(b); //静态编译时类型检查,基本数据类型
cout << a << endl;
/*
int a = 10;
char b = 'c';
a = reinterpret_cast<int>(b); //reinterpret_cast 不能将char转成int
cout << a << endl;
*/
int *intp =NULL;
char *charp = "huangxiangao";
//intp = static_cast<int*>(charp);//错误 1 error C2440: “static_cast”: 无法从“char *”转换为“int *”
intp = reinterpret_cast<int *>(charp); //主要是用于指针,有强制转换的意思
cout << charp << endl;
cout << intp << endl;
system("pause");
}