#include<iostream>//33
#include<cstdlib>
using namespace std;
/*c 风格的强制类型转化很简单,double a = 3.1415; int b = <int> 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指向的内存空间,即值,变成只读属性
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
{
public:
virtual void cry()
{
cout << "喵喵" << endl;
}
void doThing()
{
cout << "捉老鼠" << endl;
}
};
void playObjAnimal(Animal *base)
{
base->cry();//有继承 虚函数重写 父类指针指向子类对象==》多态
Dog *pDog = dynamic_cast<Dog *>(base);//父类对象==》子类对象,向下转型
if (pDog != NULL)
{
pDog->doHome();//让狗做自己特有的工作
}
Cat *pCat = dynamic_cast<Cat *>(base);
if (pCat != NULL)
{
pCat->doThing();
}
}
void printBuf(const char *p)
{
char *p1 = NULL;
p1 = const_cast<char *>(p);
//p1[0] = 'R';//通过p1去修改了内存空间,p和p1都指向这块内存空间
//cout << p1 << 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 *p1 = "RITA";
int *p2 = NULL;
//p2 = static_cast<int *>(p1);//会报错:类型转换无效
p2 = reinterpret_cast<int *>(p1);//不会报错
cout << p1 << endl;//p1所指向内存空间的内容,即字符串
cout << p2 << endl;//字符串的起始地址
//总结:通过 reinterpret_cast<>() 和 static_cast<>()把C语言的强制类型转换 都覆盖了
//===============================================================================
Cat c1;
playObjAnimal(&d1);
playObjAnimal(&c1);
//===============================================================================
char buf[] = "Rita love coding";
char *p = "Rita love coding";
printBuf(p);
system("pause");
return 0;
}
c++中的类型转换
最新推荐文章于 2022-09-30 17:44:08 发布