1#include <iostream>2#include <string>3 using namespacestd;4 classBox5 {6 Public:7 voidSetWidth (Doublewidth) {8 This->width=width;9 }Ten voidSethieght (Doubleheight) { One This->height=height; A } - voidgetwidth () { -cout<<width<<Endl; the } - Private: - DoubleWidth,height; - }; + classColorbox: Publicbox{ - Public: + voidSetColor (stringcolor) { A This->color=color; at - } - voidGetColor () { -cout <<color<<Endl; - } - in Private: - stringcolor; to }; + intMain () { - Colorbox Colorbox; the box box; *Colorbox.setcolor ("Red"); $Colorbox.sethieght (Ten);Panax NotoginsengColorbox.setwidth (Ten); - Colorbox.getcolor (); the colorbox.getwidth (); +box=Colorbox; A box.getwidth (); the //using pointers +Box *ptr; -ptr=&Colorbox; $cout<<ptr<<endl<<&box<<Endl; $Ptr->getwidth (); -Box &r1=box; - the //R1 and Box share the same piece of storage unit. You can also initialize a reference variable of a base class with a child class object - //R1 and pointer types are different, box and box*Wuyi r1.getwidth (); theBox &r2=Colorbox; - //derived class objects can be assigned or initialized to a reference to a base class object Wu //However, you cannot call a data member of a subclass, at which point the base class reference is not an alias for the derived class object, nor does it share the same storage unit with the derived class. - //It is only the alias of the base class part of the derived class, and the base class reference shares the same storage unit with the base class part in the derived class. 0027f868 About //0027f850 $ r2.getwidth (); -cout<<&r2<<endl<<&box<<Endl; - - return 0; A}
The transformation between a base class and a derived class, if the object of the base class wants to access the data member function of the subclass, it is going to be transformed.
Conversion between a C + + base class and a derived class