one, C + + can be implemented subclass to the parent class conversion, mainly divided into three forms:
1. Object Conversion: cannot implement dynamic binding, that is, polymorphism cannot be implemented.
2. Reference conversion: dynamic binding, to achieve Polymorphism.
3. Pointer conversion: dynamic binding to achieve Polymorphism.
Note: there is generally no case where the parent class is converted to a subclass.
second, the code snippet is as Follows:
1#include <iostream>2#include <string>3 4 using namespacestd;5 6 classItem_base7 {8 public:9Item_base (Const string& is,DoubleP): ISBN ( is), price (p) {}Ten stringbook () one { a returnisbn; - } - Virtual DoubleCalmoney (intC) the { - returnCprice ; - } - Private: + stringisbn; - protected: + Doubleprice ; a }; at - classBulk_item: publicItem_base - { - public: -Bulk_item::bulk_item (Const string& is,DoublePintCDoubledis): -Item_base ( is, p), min_py (c), discocunt (dis) {} in DoubleCalmoney (intC) - { to if(c >=Min_py) + { - returnc * Price *discocunt; the } * Else $ {Panax Notoginseng returnCprice ; - } the } + voidTest () a { thecout<<endl<<"sub-class test!! "<<endl; + } - Private: $ intmin_py; $ Doublediscocunt; - }; - the //reference conversions and pointer conversions enable dynamic binding, that is, polymorphic - //object Conversions do not implement dynamic bindingWuyi the //Object Conversions - voidTest_print_11 (ostream & out, item_base item,size_t n) wu { - out<<"ISBN:"<<item.book () <<"\ t Total Monkey ="<<item.calmoney (n) <<endl; about } $ - //Reference Conversions - voidTest_print_22 (ostream & out, Item_base &item,size_t N) - { a out<<"ISBN:"<<item.book () <<"\ t Total Monkey ="<<item.calmoney (n) <<endl; + } the - //Pointer Conversions $ voidTest_print_33 (ostream & out, Item_base *item,size_t N) the { the out<<"ISBN:"<<item->book () <<"\ t Total Monkey ="<<item->calmoney (n) <<endl; the } the - intMain () in { theItem_base Item ("X-123-1234-x",10.0); the aboutBulk_item item2 ("123-456-x",10.0,Ten,0.8); the theTest_print_11 (cout,item,Ten);//object Conversions do not implement polymorphism theTest_print_11 (cout,item2,Ten); + -cout<<endl; theTest_print_22 (cout,item,Ten);//Reference ConversionsBayiTest_print_22 (cout,item2,Ten); the thecout<<endl; -Test_print_33 (cout,&item,Ten);//Pointer Conversions -Test_print_33 (cout,&item2,Ten); the return 0; the}
C + + Learning basics 10--transformation of a subclass object into a parent class object