类似C语言强制类型转换
1.可以用做基本数据类型转换
2.把空类型的指针转换为目标指针类型
3.不能转换带有const属性指针
提供一个常属性的接口
说基本没用到
#include <iostream>
struct MM
{
char* name;
int age;
void setData(const char* mmName, int mmAge)
{
name = const_cast<char*>(mmName);
age = mmAge;
}
void printfData()
{
std::cout << name << "\t" << age << std::endl;
}
};
//1.基本类型转换
void TestTransform()
{
//1.基本类型转换
//C
int cnum = (int)1.1;
std::cout << cnum << "\n";
//C++方式
int cppNum = int(1.2);
std::cout << cnum << "\n";
}
void TestStatic_cast()
{
//C++提供的安全
double dNum = 1.11;
//static_cast<要转换的类型>(要转换的东西:表达式也可以)
int num = static_cast<int>(dNum);
std::cout << dNum << "\n";
//const类型转换:增加const
double eNum= 2.22;
const int fNum = static_cast<const int>(eNum);
std::cout << fNum << "\n";
const int cData = 1;
//错误用法
//int* pData = static_cast<int*>(&cData);
int* pData = const_cast<int*>(&cData);
std::cout << (*pData)+2000 << "\n";
MM m1;
m1.setData("喜德盛", 19);
m1.printfData();
char name[20] = "永久";
MM m2;
m2.setData(name, 18);
m2.printfData();
}
int main()
{
std::cout << "Hello World!\n";
TestStatic_cast();
}