17.4 上机实践习题
1.尝试定义一个包含虚函数的基类,然后将这个类作为基类,再派生1个子类,最后用dynamic_cast进行类型安全转换。
【提示】上述题目主要是要求读者熟悉dynamic_cast操作符的相关知识,重点是掌握操作符的作用及其使用。
【关键代码】
01 #include<iostream> 02 using namespace std; 03 04 class base//基类定义 05 { 06 public: 07 virtual void disp()//虚函数 08 { 09 cout<<"hello,base"<<endl; 10 } 11 }; 12 class child:public base//派生类定义 13 { 14 public: 15 void disp() 16 { 17 cout<<"hello,child1"<<endl; 18 } 19 }; 20 21 //main()函数的实现 22 base*pbase=new child; 23 childpchild=dynamic_cast<child>(pbase); 24 if(pchild!=NULL) 25 { 26 pchild->disp(); 27 } 28 else 29 cout<<"转换不安全,退出"<<endl; 30 base*pbase1=new base; 31 childpchild1=dynamic_cast<child>(pbase1);//转换并不安全 32 if(pchild1!=NULL) 33 { 34 pchild1->disp(); 35 } 36 else 37 cout<<"转换不安全,退出"<<endl;
2.尝试使用const_cast、static_cast和reinterpret_cast操作符,来进行类型转换并输出结果。
【提示】上述题目主要是要求读者掌握类型转换操作符的相关知识,重点是操作符的使用。
【关键代码】
01 int i=5; 02 const int*ci=&i; 03 (const_cast<int>(ci))=8;//去除了const属性 04 cout<<i<<endl; 05 cout<<(*ci)<<endl; 06 07 double d=static_cast<double>(i); 08 int j=static_cast<int>(d); 09 10 double n=2. 5; 11 double*p=&n; 12 int*pc=NULL; 13 pc=reinterpret_cast<int*>(p);//指针间的相互转换,地址赋值 14 cout<<(*pc)<<endl;