c++与c的数据类型转换

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 (a)
TYPE为需要转换成的类型

1.静态类型转换与重新解释类型转换

void 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 = "hello...itcast ";
	int		*p2 = NULL;
	//p2 = static_cast<int*>(p1); // 类型转换无效 static_cast不适合用来将不同类型的数据进行转换

	p2 = reinterpret_cast<int *>(p1); //若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
	cout << "p1:" << p1 << endl; //%s
	cout <<"p2" << p2 << endl; //%d
	//总结:通过 reinterpret_cast<>() 和 static_cast<>()把C语言的强制类型转换 都覆盖了..
}

2.动态类型转换—用于子类和父类之间的多态类型转换(实现子类可以利用多态调用自己特有的成员函数)

class Tree 
{

};
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 playObj(Animal *base)//搭建舞台,实现多态
{
	base->cry(); // 1有继承 2虚函数重写 3 父类指针(引用) 指向子类对象  ==>多态
	//能识别子类对象
	// dynamic_cast 运行时类型识别  RIIT   如果不是指定的类型,那么会识别失败,则指针会变为空null,如果是指定的识别类型,那么指针不会置为null
	Dog *pDog = dynamic_cast<Dog *>(base);
	cout << "lalalallal"<<pDog<<endl;
	if (pDog != NULL)
	{
		pDog->doHome(); //让狗做自己 特有的工作 
	}
	Cat *pCat = dynamic_cast<Cat *>(base);	//父类对象 ===> 子类对象 
											//向下转型  
											//把老子 转成 小子 
	if (pCat != NULL)
	{
		pCat->doThing();  //让猫 做自己 特有的工作 
	}
}
void main()
{
	Dog d1;
	Cat c1;
	Animal *pBase = NULL;
	pBase = &d1;
	pBase = static_cast<Animal *>(&d1); //让C++编译在编译的时候进行 类型检查 
	//强制类型转换 
	pBase = reinterpret_cast<Animal *>(&d1); 	
	{
		Tree t1;
		//pBase = static_cast<Animal *>(&t1); //类型转换无效(不同类之间不能互相转换)  C++编译器会做类型检查
		pBase = reinterpret_cast<Animal *>(&t1);  //reinterpret_cast 重新解释 ....强制类转换的味道
	}
	playObj(&d1);
	playObj(&c1);
	system("pause");
}

3.去除const属性

//const char *p 的const修饰 让p指向的内存空间 变成只读属性
void printBuf(const char* p)
{
	char *p1 = NULL;
	//const char * ===> char * //把只读属性 去掉
	p1 = const_cast<char *>(p);
	p1[0] = 'Z' ;  //通过p1 去修改了内存空间
	cout << p << endl;
}
void main()
{
	char buf[] = "aaaaaaaaafffffddd";
	char *myp = "aaaaaaaaafffffddd";//内存空间一旦修改,则会造成剩余空间变大或超出原有内存空间大小
	printBuf (buf);
	//printBuf (myp);//要确保 p所指向的内存空间 确实能修改 ;如果不能修改会带来灾难性后果
	system("pause");
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值