001c语言中的基本数据类型转换与c++中比较

#include<iostream>
using namespace std;
/*
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)
  */
int main(void)
{
	double dpi = 3.1415926;
	int number1 = (int)dpi;//C类型转换
	int number2 = static_cast<int>(dpi);//c++类型转换, 静态类型转换  编译的时c++编译器会做类型检查
	int number3 = dpi;//c语言中可以进行隐式类型转换的地方,均可使用 static_cast<>() 进行类型转换

	cout << number1 << endl;
	cout << number2 << endl;
	cout << number3 << endl;

	//char* ===> int *
	char*p1 = "jisuanjizuchegnyuanli";
	int*p2 = NULL;
	//p2 = static_cast<int*>(p1);//error C2440: “static_cast”: 无法从“char *”转换为“int *”
	// 使用static_cast, 编译器编译时,会做类型检查 若有错误 提示错误
	p2 = reinterpret_cast<int*>(p1); //若不同类型之间,进行强制类型转换,用reinterpret_cast<>() 进行重新解释
	//输入的是内存首地址
	cout << "p1:" << p1 << endl;
	cout << "p2" << p2 << endl;
	//总结:通过 reinterpret_cast<>() 和 static_cast<>()把C语言的强制类型转换 都覆盖了..

	system("pause");
	return 0;
}
/*
 * 
3
3
3
p1:jisuanjizuchegnyuanli
p200BFDA54
请按任意键继续. . .

 */

猜你喜欢

转载自blog.csdn.net/baixiaolong1993/article/details/89488011