类型转换

今天回帖的时候偶然看到了一些类型转换的东西,正好彻底补了补课,

C++一共四种类型转换修饰:

 

1.reinterpret_cast<new_type>(expression)

 

暴力型,直接改变类型指针的值,不做内容检查和转换

#include <iostream> using namespace std; class base1{public:}; class base2 {public:}; class Base { virtual void dummy() {} }; class Derived : public Base {}; void main(void) { base1 *p1=new base1; base2 *p2=new base2; Base *p3=new Base; Derived *p4=new Derived; reinterpret_cast <base1*>(p2); reinterpret_cast <Derived*>(p3); }

任意互转,儿子指父亲,这都没问题!

 


2.dynamic_cast<new_type>(expression)

#include <iostream> using namespace std; class base1{public:}; class base2 {public:}; class Base { virtual void dummy() {} }; class Derived : public Base {}; int main(void) { base1 *p1=new base1; base2 *p2=new base2; Base *p3=new Base; Derived *p4=new Derived; //base1* p5 = dynamic_cast <base1*>(p2);//编译报错is not a polymorphic type,只能做继承转换 Derived* p6= dynamic_cast <Derived*>(p3); Base* p7 = dynamic_cast <Base*>(p4); return 0; }

 

不能任意转,只能用于继承关系转换,而且,儿子指父亲可以,但是结果(p6)为NULL

父亲指儿子是没有问题的!

 


3.static_cast<new_type>(expression)

 

#include <iostream> using namespace std; class base1{public:}; class base2 {public:}; class Base { virtual void dummy() {} }; class Derived : public Base {}; int main(void) { base1 *p1=new base1; base2 *p2=new base2; Base *p3=new Base; Derived *p4=new Derived; char i ='a'; //base1* p5 = static_cast <base1*>(p2);//进行类型检查,不让转 int lpt = static_cast <int>(i); // 类型检查可以转的,就让你转 Derived* p6= static_cast <Derived*>(p3); Base* p7 = static_cast <Base*>(p4); return 0; }

做类型转换检查,但是儿子指父亲这种就没法了,还是让他转了

父亲指儿子没有问题

 


4.const_cast<new_type>(expression)

 

#include <iostream> using namespace std; class base1{public:}; class base2 {public:}; class Base { virtual void dummy() {} }; class Derived : public Base {}; int main(void) { const base1* a = new base1; base1* b = const_cast <base1*>(a); return 0; }


用于去const,这个也比较威猛

 

 

 

 

大概就是如此了,今天又学到一点

 

你可能感兴趣的:(c,null,Class,iostream)