Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5493199
  • 博文数量: 922
  • 博客积分: 19333
  • 博客等级: 上将
  • 技术积分: 11226
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-27 14:33
文章分类

全部博文(922)

文章存档

2023年(1)

2020年(2)

2019年(1)

2017年(1)

2016年(3)

2015年(10)

2014年(17)

2013年(49)

2012年(291)

2011年(266)

2010年(95)

2009年(54)

2008年(132)

分类: C/C++

2011-08-22 10:44:58

一个代码用来说明问题,如下:
  1. 1 //程序功能:
  2.   2 //static_cast,dynamic_cast
  3.   3 //父子类之间的转换
  4.   4 //一个可能的输出结果如下:
  5.   5 //&b:0xbf91be28
  6.   6 //&d:0xbf91be20
  7.   7 //38pb:0xbf91be20
  8.   8 //40pb:0xbf91be20
  9.   9 //42pb:0xbf91be20
  10.  10 //47pd:0xbf91be28
  11.  11 //结论:父指针指向子对象地址,不用强转,即可。
  12.  12 //子指针指向父对象地址,只有static_cast可以编译通过。
  13.  13 #include <iostream>
  14.  14 using std::cout;
  15.  15 using std::endl;
  16.  16 class Base
  17.  17 {
  18.  18 public:
  19.  19 Base(){a1=1;}
  20.  20 int a1;
  21.  21 };
  22.  22 class Derive:public Base
  23.  23 {
  24.  24 public:
  25.  25 Derive(){a2=2;}
  26.  26 int a2;
  27.  27 };
  28.  28 int main(int argc, char *argv[])
  29.  29 {
  30.  30 Base *pb;
  31.  31 Derive *pd;
  32.  32 Base b;
  33.  33 Derive d;
  34.  34 cout <<"&b:"<<&b<<endl;
  35.  35 cout<<"&d:"<<&d<<endl;
  36.  36
  37.  37 pb=&d;
  38.  38 cout<<__LINE__<<"pb:"<<pb<<endl;
  39.  39 pb=static_cast<Base*>(&d);
  40.  40 cout<<__LINE__<<"pb:"<<pb<<endl;
  41.  41 pb=dynamic_cast<Base*>(&d);
  42.  42 cout<<__LINE__<<"pb:"<<pb<<endl;
  43.  43
  44.  44 //pd=&b;//error
  45.  45 //cout<<__LINE__<<"pd:"<<pd<<endl;
  46.  46 pd=static_cast<Derive*>(&b);
  47.  47 cout<<__LINE__<<"pd:"<<pd<<endl;
  48.  48 //pd=dynamic_cast<Derive*>(&b);//error
  49.  49 //cout<<__LINE__<<"pd:"<<pd<<endl;
  50.  50
  51.  51 return 0;
  52.  52 }


阅读(1869) | 评论(0) | 转发(0) |
0

上一篇:cp自动创建层级结构的例子

下一篇:真的

给主人留下些什么吧!~~