C++新特性 强制转换static_cast
/*
强制类型转换时具有一定风险的,有的转换并不一定安全,如果把整数数值转换成指针,把基类指针转换成派生指针
把函数指针转换成另外一种函数指针,把常量指针转换成非常量指针等
1.const_cast 只针对指针,引用,this 去除const属性
2.static_cast 基本等价于隐式转换的一种类型转换运算符,可使用于需要明确隐转换的地方
3.reinterpret_cast
4.dynamic_cast
*/
//static_cast 基本等价于隐式转换的一种类型转换运算符,可使用于需要明确隐转换的地方
class Cint
{
public:
operator int()
{
return m_nInt;
}
int m_nInt;
};
class Base
{
public:
Base();
~ Base();
private:
};
class son:public Base
{
public:
son();
~son();
private:
};
int main()
{
int n = 5;
float f = 10.f;
//本质发生了隐转换
f = n;
//明确转换,便于维护
f = static_cast<float>(n);
//低风险转换:整型与浮点型丢失精度
f = static_cast<float>(n);
char ch = 'a';
n = static_cast<int>(ch);
//void* 指针转换
void* p = nullptr;
int * pN = static_cast<int *>(p);
//转换运算符的方式
Cint nobj;
int a = static_cast<int> (nobj); // 如果没有重载operator int()无法通过
//高风险
int kk;
char * p;
p = kk;//无法转换,整数与指针类型的转换,即使加上static_cast也无法转换成功
int*pk;
char * k = static_cast<char*>(pk); //C语言可以,但是C++不行
Base * base = nullptr;
son * son01 = nullptr;
//父类转子类(不安全)
son01 = base;//无法通过
son01 = static_cast<son*>(base); //编译能通过不安全,编译时不检查类型,做了强制转换
//子类转父类(安全)
base = son01;
}
版权声明:本文为hmd3394969原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。