C++的类型转换详细介绍
1、类型转换名称和语法
C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:
TYPE b = (TYPE)a
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
static_cast 静态类型转换。如int转换成char
reinterpreter_cast 重新解释类型
dynamic_cast 命 名上理解是动态类型转换。如子类和父类之间的多态类型转换。
const_cast 字面上理解就是去const属性。
4种类型转换的格式:
TYPE B = static_cast<TYPE> (a)
2、类型转换一般性介绍
4中类型转化介绍
1)static_cast<>() 静态类型转换,编译的时c++编译器会做类型检查;
基本类型能转换 但是不能转换指针类型
2)若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
3)dynamic_cast<>(),动态类型转换,安全的基类和子类之间转换;运行时类型检查 (C++特有的)
4)const_cast<>(),去除变量的只读属性(C++特有的),变量的类型必须是指针,指针指向的内存空间可被修改
一般性结论
C语言中 能隐式类型转换的,在c++中可用 static_cast<>()进行类型转换。因C++编译器在编译检查一般都能通过;
C语言中不能隐式类型转换的,在c++中可以用 reinterpret_cast<>() 进行强行类型 解释。
static_cast<>()和reinterpret_cast<>() 基本上把C语言中的 强制类型转换给覆盖
reinterpret_cast<>()很难保证移植性。
3、典型案例
代码中包含了4中类型转化的实例,以及注意点。
#include<iostream>
using namespace std;
class Animal
{
public:
 virtual void action()
 {
 cout<<"the action is animal's "<<endl;
 }
};
class Dog:public Animal
{
public:
 virtual void action()
 {
 cout<<"the action is dog's "<<endl;
 }
 void doSwim()
 {
 cout<<"the dog is swimming..."<<endl;
 }
};
class Cat:public Animal
{
public:
 virtual void action()
 {
 cout<<"the action is cat's "<<endl;
 }
 void doTree()
 {
 cout<<"the cat is claming tree..."<<endl;
 }
};
class Desk
{
public:
 void action()
 {
 cout<<"this is Desk, not belong Animal"<<endl;
 }
};
void ObjPlay(Animal *animl)
{
 animl->action();
 Dog *dog = dynamic_cast<Dog *>(animl);
 if(dog!=NULL) //判断是不是dog
 {
 dog->action();
 dog->doSwim();
 }
 Cat *cat = dynamic_cast<Cat *>(animl);
 if(cat!=NULL) //判断是不是cat
 {
 cat->action();
 cat->doTree();
 }
 cout<<"func ObjPlay is exit!!!\n"<<endl;
}
//典型用法 把形参的只读属性去掉
void Opbuf(const char *p)
{
 cout << p << endl;
 //char *p2 = p; err:const char *不能初始化为char *
 //p[0] = 'b'; err:必须是可修改的左值
 char *p2 = const_cast<char*>(p); //去除只读的属相
 p2[0] = 'b';
 cout << p << endl;
}
int main()
{
 //静态类型转化 static_cast<>()
 double d = 3.14159;
 int i1,i2;
 i1 = d; //C中的隐式类型转化
 i2 = static_cast<int>(d); //C++中的静态类型转化
 cout<<"C中类型转化:"<<i1<<endl;
 cout<<"C++中类型转化:"<<i2<<endl;
 //重新解释类型reinterpret_cast<>()
 char *p = "abcd";
 int *p1 = NULL;
 int *p2 = NULL;
 p1 = (int *)p; //C中强制类型转化
 //p2 = static_cast<int *>(p);  编译报错,类型转化错误,静态类型不能转化指针
 p2 = reinterpret_cast<int *>(p); //C++中的重新解释类型
 cout<<"C中类型转化"<<hex<<*p1<<endl;
 cout<<"C++中类型转化:"<<hex<<*p2<<endl;
 //动态类型转换 dynamic_cast<>()
 Animal an;
 Animal *pAn = &an;
 ObjPlay(pAn);
 Dog dog;
 Dog *pDog = &dog;
 ObjPlay(pDog);
 Cat cat;
 Cat *pCat = &cat;
 ObjPlay(pCat);
 Desk desk;
 Desk *pDesk = &desk;
 //Animal *pAn = dynamic_cast<Animal*>(pDesk); 不同的基类指针之间不能相互转化,安全
 //去除变量的只读属性,const_cast<>(),此类型必须是指针
 char buf[100] = "aaaaaaaaaaaa";
 //Opbuf(buf);
 //要保证指针所执行的内存空间能修改才行 若不能修改 还是会引起程序异常
 //Opbuf("dddddddddddsssssssssssssss");
 system("pause");
 return 0;
}
 
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
