C++学习基础十一——子类对象向父类对象的转化

一、C++中可以实现子类向父类的转换,主要分为三种形式:

1.对象转换:不能实现动态绑定,即不能实现多态。

2.引用转换:动态绑定,实现多态。

3.指针转换:动态绑定,实现多态。

注意:一般不会出现父类转化为子类的情况。

 

二、代码片段如下:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 class Item_base
 7 {
 8 public:
 9     Item_base(const string &is,double p):isbn(is),price(p){}
10     string book()
11     {
12         return isbn;
13     }
14     virtual double calMoney(int c)
15     {
16         return c * price;
17     }
18 private:
19     string isbn;
20 protected:
21     double price;    
22 };
23 
24 class Bulk_item : public Item_base
25 {
26 public:
27     Bulk_item::Bulk_item(const string &is,double p,int c,double dis):
28         Item_base(is,p),min_py(c),discocunt(dis){}
29     double calMoney(int c)
30     {
31         if(c >= min_py)
32         {
33             return c * price * discocunt;
34         }
35         else
36         {
37             return c * price;
38         }
39     } 
40     void test()
41     {
42         cout<<endl<<"子类测试!!"<<endl;
43     }
44 private:
45     int min_py;
46     double discocunt;
47 };
48 
49 //引用转换和指针转化可以实现动态绑定,即多态
50 //对象转化不能实现动态绑定
51 
52 //对象转化 
53 void test_print_11(ostream &out,Item_base item,size_t n)
54 {
55     out<<"ISBN :"<<item.book()<<"	 total monkey = "<<item.calMoney(n)<<endl;
56 } 
57 
58 //引用转换
59 void test_print_22(ostream &out,Item_base &item,size_t n)
60 {
61     out<<"ISBN :"<<item.book()<<"	 total monkey = "<<item.calMoney(n)<<endl;
62 }  
63 
64 //指针转换
65 void test_print_33(ostream &out,Item_base *item,size_t n)
66 {
67     out<<"ISBN :"<<item->book()<<"	 total monkey = "<<item->calMoney(n)<<endl;
68 } 
69 
70 int main()
71 {
72     Item_base item("x-123-1234-x",10.0);
73     
74     Bulk_item item2("123-456-x",10.0,10,0.8);
75     
76     test_print_11(cout,item,10);//对象 转换不能实现多态 
77     test_print_11(cout,item2,10);
78     
79     cout<<endl;
80     test_print_22(cout,item,10);//引用转换 
81     test_print_22(cout,item2,10);
82     
83     cout<<endl;
84     test_print_33(cout,&item,10);//指针转换 
85     test_print_33(cout,&item2,10);
86     return 0;
87 }
 
 
原文地址:https://www.cnblogs.com/calence/p/5894590.html