四种强制类型转换之一static_cast
Page 1 of 1
四种强制类型转换之一static_cast
static_cast
-可以在继承体系内转来转去,比如父类到子类,子类到父类
-所有内置类型之间的转换
-空指针转换成目标类型的空指针,任何类型转换成void
-可以用来加上const,volatile或者__unaligned属性,但无法去除他们(使用const_cast)
-static_cast不如dynamic_cast来的安全,因为不是动态检查
-失败时,static_cast会好像什么事也没有返回(和dynamic_cast不一样,dynamic返回原本的指针)
-由于static_cast并不安全,所以使用之前确保转换是安全的
class grandfather {};
class father:public grandfather {};
class son:public father {};
int main()
{
grandfather *gf = new grandfather;
father *f = static_cast(gf); //static_cast,grandfather to father
son *s = static_cast(gf); //grandfather to son //到孙类也行
father *f2 = static_cast(s); //son to father
int integer = 88;
int integer2 = static_cast(integer); //add const
return 0;
}
小弟知识浅浅,若有幸发现错误,望大神伸出援手,指点迷津
-可以在继承体系内转来转去,比如父类到子类,子类到父类
-所有内置类型之间的转换
-空指针转换成目标类型的空指针,任何类型转换成void
-可以用来加上const,volatile或者__unaligned属性,但无法去除他们(使用const_cast)
-static_cast不如dynamic_cast来的安全,因为不是动态检查
-失败时,static_cast会好像什么事也没有返回(和dynamic_cast不一样,dynamic返回原本的指针)
-由于static_cast并不安全,所以使用之前确保转换是安全的
class grandfather {};
class father:public grandfather {};
class son:public father {};
int main()
{
grandfather *gf = new grandfather;
father *f = static_cast
son *s = static_cast
father *f2 = static_cast
int integer = 88;
int integer2 = static_cast
return 0;
}
小弟知识浅浅,若有幸发现错误,望大神伸出援手,指点迷津
too wei- Sponsor
- Posts : 31
Points : 66331
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|