dynamic_cast与static_cast使用

dynamic_cast与static_cast用于子类与基类之间的转换。

首先dynamic_cast:

 1 #include <iostream>
 2 using namespace std;
 3 class A{
 4     public:
 5         virtual ~A(){} //使用dynamic_cast时,必要!
 6 };
 7 class B:public A{
 8     public:
 9         B(){
10             m_b=12;
11         }
12         void foo(){
13             cout<<"B: "<<m_b<<endl;
14         }
15     private:
16         int m_b;
17 };
18 int main()
19 {    
20     A *a=new B();
21     B *b=dynamic_cast<B*>(a);
22     b->foo();
23     delete a;
24     return 0;
25 }

上面没有virtual ~A(){},编译时会报错:(source type is not polymorphic)。

static_cast:

 1 #include <iostream>
 2 using namespace std;
 3 class A{
 4     public:
 5         A():m_a(32){}
 6         void foo(){
 7             cout<<"A: "<<m_a<<endl;
 8         }
 9         void setA(int a){
10             m_a=a;
11         }
12     private:
13         int m_a;
14 };
15 class B:public A{
16     public:
17         B(){
18             m_b=12;
19             setA(13);
20         }
21         void foo(){
22             cout<<"B: "<<m_b<<endl;
23         }
24     private:
25         int m_b;
26 };
27 int main()
28 {    
29     A *a=new B();
30     B *b=static_cast<B*>(a);
31     A *aa=static_cast<A*>(b);
32     b->foo();
33     aa->foo();
34     delete a;
35     return 0;
36 }

打印a、b、aa地址,可知地址一样。

转载于:https://www.cnblogs.com/wuchaofan/p/3378170.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值