类型转换名称和语法
C风格的强制类型转换(Type Cast)很简单,不管是这么类型的转换统统是
TYPE b = (TYPE)a;
C++风格的类型转换提供了四种类型转换操作符,类应对不同场合的应用
static_cast 静态类型转换。如int转换成char
reinterpreter_cast 重新解释类型
dynamic_cast 动态类型转换,如子类和父类之间多态雷子那个转换
const_cast 字面上理解就是去const属性
4种类型转换的格式
TYPE B = static_cast (a);
类型转换一般性介绍
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;
/*
C 风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是:
TYPE b = (TYPE)a
C++风格的类型转换提供了 4 种类型转换操作符来应对不同场合的应用。
static_cast 静态类型转换。如 int 转换成 char
reinterpret_cast 重新解释类型
dynamic_cast 命名上理解是动态类型转换。如子类和父类之间的多态类型转换。
const_cast, 字面上理解就是去 const 属性。
4 种类型转换的格式:
TYPE B = static_cast<TYPE> (a)
*/
//const char *p中的const修饰,让p指向的内存空间变成只读属性
void printBuf(const char *p)
{
//p[0] = 'y'; //err 给只读空间赋值
char *p1 = NULL;
p1 = const_cast<char *>(p); //把只读属性去掉
p1[0] = 'y';
cout << p1<< endl;
}
void main() //const_cast
{
char buf[] = "lijiatu";
printBuf(buf);
system("pause");
}
class Tree {};
class Animal
{
public:
virtual void cry() = 0;
private:
};
class Dog : public Animal
{
public:
virtual void cry() //虚函数重写
{
cout << "汪汪" << endl;
}
void doHome()
{
cout << "看家" << endl;
}
private:
};
class Cat : public Animal
{
public:
virtual void cry() //虚函数重写
{
cout << "喵喵" << endl;
}
void doThing()
{
cout << "抓老鼠" << endl;
}
private:
};
void playobj(Animal *base) //面向抽象类编程 :
{
base->cry(); //1、有继承 2、虚函数重写 3、父类指针指向子类对象 ===>多态
//dynamic_cast 运行时类型识别
Dog* pDog = dynamic_cast<Dog*>(base);
if (pDog != NULL)
pDog->doHome();
Cat* pCat = dynamic_cast<Cat*>(base); //父类对象转为子类对象 向下转型
if (pCat != NULL)
pCat->doThing();
}
void main02()
{
Dog d1;
Cat c1;
playobj(&d1);
playobj(&c1);
Animal *pBase = NULL;
pBase = &d1;
pBase = static_cast<Animal *>(&d1); //让C++编译的时 c++编译器会做类型检查
pBase = reinterpret_cast<Animal *>(&d1); //强制类型转换
{
Tree t1;
//pBase = static_cast<Animal *>(&t1); err
pBase = reinterpret_cast<Animal *>(&t1); //强制类型转换
}
system("pause");
}
void main01()
{
double PI = 3.1415926;
int num = (int)PI; //C风格的类型转换
int num2 = static_cast<int>(PI); //C++的类型转换 编译的时 c++编译器会做类型检查
int num3 = PI; //C语言中 隐式类型转换的地方,均可使用static_cast<>()进行类型转换
char *p1 = "hello wangbaoming ";
int *p2 = NULL;
//p2 = static_cast<int *>(p1); err
p2 = reinterpret_cast<int *>(p1); //强制类型转换
cout << "p1: " << p1 << endl; //%s
cout << "p2: " << p2 << endl; //%d
//总结:通过static_cast 和reinterpret_cast把C语言的强制类型转换都覆盖了
system("pause");
}
总结
结论 1:程序员要清除的知道: 要转的变量,类型转换前是什么类型,类型转换后是什么类
型。转换后有什么后果。
结论 2:一般情况下,不建议进行类型转换;避免进行类型转换。