C++ 风格的类型转换
C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统都是
TYPE b = (TYPE)a;
C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
- static_cast 静态类型转化。如int转换为char
- reinterpret_cast 重新解释类型
- dynamic_cast 动态类型转换。如子类和父类之间的多态类型转换
- const_cast 去const属性
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统都是
//TYPE b = (TYPE)a;
//C++风格的类型转换提供了4种类型转换操作符来应对不同场合的应用。
//1 static_cast 静态类型转化。如int转换为char
//2 reinterpret_cast 重新解释类型
//3 dynamic_cast 动态类型转换。如子类和父类之间的多态类型转换
//4 const_cast 去const属性
//4种类型转换的格式:
//以 1 为例:TYPE B = static_cast<TYPE>(a);
class Animal
{
public:
virtual void cry() = 0;
protected:
private:
};
class Dog :public Animal
{
public:
virtual void cry()
{
cout << "woof woof woof!" << endl;
}
void watchHome()
{
cout << "Watch home!" << endl;
}
};
class Cat :public Animal
{
public:
virtual void cry()
{
cout << "mew mew mew!" << endl;
}
void watchHome()
{
cout << "Catch rats!" << endl;
}
};
void playObj(Animal* base)
{
//base->cry();//实现多态
//dynamic_cast运行时类型识别
Dog* pDog = dynamic_cast<Dog*>(base);//父类对象====>子类对象
//可实现向下转型:把老子转成小子
if (pDog != NULL)
{
pDog->cry();
pDog->watchHome();
}
Cat* pCat = dynamic_cast<Cat*>(base);
if (pCat != NULL)
{
pCat->cry();
pCat->watchHome();
}
}
void printBuf(const char* p)
{
char* p1 = NULL;
//程序员要清楚的知道 变量转换前是什么类型,转换之后是什么类型
//const char* ====> char* :去掉只读属性
p1 = const_cast<char*>(p);
p1[0] = 'X';
p1[1] = 'V';
cout << endl << p << endl;
}
int main()
{
double dpi = 3.1415926;
int num1 = (int)dpi;//C类型转换
int num2 = static_cast<int>(dpi);//静态类型转换 编译时C++编译器会做类型检查
int num3 = dpi;//C语言中可以隐式类型转换的地方,均可使用`static_cast<>()`进行类型转换
//char* ===> int*
char* p1 = new char[100];
strcpy(p1, "helloWorld!");
int* p2 = NULL;
//p2 = static_cast<int*>(p1);//使用static_cast,编译器编译时会做类型检查,有错报错
p2 = reinterpret_cast<int*>(p1);//用reinterpret_cast<>()进行重新解释
cout << "p1: " << p1 << endl;//输出本身
cout << "p2: " << p2 << endl << endl;//输出首地址的十进制表示
//总结:通过static_cast<>()和reinterpret_cast<>()把C语言的强制类型转化都覆盖了
//static_cast<>()和reinterpret_cast<>()各司其职,不能混用
delete[] p1;
Dog d1;//dynamic_cast<>();
Cat c1;
Animal* pBase = NULL;
pBase = &d1;
pBase = static_cast<Animal*>(&d1);//C++编译器在编译的时候进行类型检查,故可通过
pBase = reinterpret_cast<Animal*>(&d1);//重新解释类型
playObj(&d1);
playObj(&c1);
char buf[] = "aaaaaaaaaaaaaaaaa";
printBuf(buf);
return 0;
}
输出
p1: helloWorld!
p2: 00115378
woof woof woof!
Watch home!
mew mew mew!
Catch rats!
XVaaaaaaaaaaaaaaa