//C++新特性 强制转换const_cast
/*
强制类型转换时具有一定风险的,有的转换并不一定安全,如果把整数数值转换成指针,把基类指针转换成派生指针
把函数指针转换成另外一种函数指针,把常量指针转换成非常量指针等
1.const_cast 只针对指针,引用,this 去除const属性
2.static_cast
3.reinterpret_cast
4.dynamic_cast
*/
class CTest
{
public:
CTest() :m_nTest(2){}
void foo(int nTest) const
{
m_nTest = nTest;//错误,由于常成员函数,无法修改参数
const_cast<CTest*> (this)->m_nTest = nTest;//这样可以修改
}
public:
int m_nTest;
};
int main()
{
int n = 1;
int * p = &n;//编译能过
int * p = n; //编译报错,
int * p1 = (int *)n; //编译能过,将地址为1的指针赋值,执行会奔溃
//基类-->派生类 强转 会出错 强转隐患很多
//规范转换
const int n = 5;
const std::string s = "hdm";
//只针对指针,引用,this
std::string t = const_cast<std::string>(s);//错误
int k = const_cast<int>(n);//错误
int * k = const_cast<int*> (&n);
int& kRef = const_cast<int &>(n);
}