static_cast
double d = 1.2;
//static_cast 普通数据类型之间的强转,不能指针之间转换
//static_cast 是在编译期间进行转换的,在运行时不能检测类型,所以类型转换之间存在风险
int b = static_cast<int>(d);
/*不能指针之间转换
int *pb = static_cast<int*>(&d);*/
static_cast 也可以用于继承关系的类对象之间的转换 和 类指针之间的转换
class Animal
{
public:
virtual void eat()
{
printf("动物吃饭\n);
}
}
class Cat :public Animal
{
public:
virtual void eat()
printf ("猫吃饭\n");
}
void CatchMouse()
{
printf ("猫抓老鼠\n");
}
};
Cat *pc = new Cat;
Animal *pa = static_cast<Animal *>(pc);
reinterpret_cast
//不同类型的指针之间的转换只能用 reinterpret_cast 转换
//Student *ps = static_cast<Student*>(pc);编译报错: 无法从“Cat *”转换为“Student *”
class Student
{
;
};
Cat *pc = new Cat;
Student *ps = reinterpret_cast<Student*>(pc);
//reinterpret_cast 也可以用于整数和指针之间的转换
//reinterpret_cast 可以进行任意类型指针之间的转换
//reinterpret_cast 是直接从二进制位 进行赋值,是一种既不安全的转换
dynamic_cast
主要用于类层次之间的转换,也用于类之间的交叉转换
dynamic_cast 具有类型检侧的功能,比static_cast 安全
class Animal
{
public:
virtual void eat()
{
printf("动物吃饭\n");
}
};
class Cat :public Animal
{
public:
virtual void eat()
{
printf ("猫吃饭\n");
}
void CatchMouse()
{
printf ("猫抓老鼠\n");
}
};
class Dog :public Animal
{
public:
virtual void eat()
{
printf ("狗吃饭\n");
}
void lookHome()
{
printf ("狗看家\n");
}
};
void func(Animal *pa)
{
pa->eat();
//根据特殊的对象做一些特殊的事情
//dynamic_cast 将基类指针转换为派生类指针
//1、如果这个基类指针指向确实是要转化的派生类类型的对象,返回指向这个对象的指针
//2、如果这个基类指针指向的不是要转化的派生类类型的对象, 返回的是空指针 NULL
Cat *pc = dynamic_cast<Cat*>(pa);
if (pc != NULL)
{
cout << "基类指针指向Cat"<< endl;
pc->CatchMouse();
}
Dog *pd = dynamic_cast<Dog*>(pa);
if (pd != NULL)
{
cout << "基类指针指向Dog"<< endl;
pd->lookHome();
}
}
int main()
{
Animal a;
Cat c;
Dog d;
func(&a);
func(&c);
func(&d);
return 0;
}
const_cast
转换时去掉变量的常量属性 然后赋值
void func2(const char *s)
{
//在转化的过程中去掉 s 的 const属性并将值赋值给 p
//注意: 转换完之后, s的属性是不变的,s本身还是据用 const属性
char *p = const_cast<char*>(s);
p[0] = 'w';
}
int main()
{
//str是一个字符数组
char str[] = "hello world";
func2(str);
cout << str << endl;
return 0;
}