1. Easy to expand the program so that it does not have to rewrite the entire program
code example
1#include <iostream>2#include <string>3 using namespacestd;4 classFather5 {6 protected:7 stringname;8 inttall;9 Public:TenFatherstringAinti); OneFather () {cout <<"construct base class \ n"; } A voidPrint () {cout << name <<"height is"<< Tall <<"\ n"; } -~father () {cout <<"release base class object \ n"; } - }; the /*-------------is equivalent to the function of the original program-------------*/ -Father::father (stringAinti) - { -cout <<"\ n In the constructor of the base class \ n"; +Name =A; -Tall =i; + print (); Acout <<"leave the base class constructor \ n"; at } - classSon: PublicFather - { - Private: - intweight; - Public: inSonstringAintIintj); - voidprint1 (); to~son () {cout <<"\ nthe subclass object is released \ n"; } + }; - /*--------is equivalent to adding new functionality to the original program functionality-----------*/ theSon::son (stringAintIintj) * { $Name =A;Panax NotoginsengTall =i; -cout <<"\ n in the subclass constructor \ n"; theWeight =J; + } A voidson::p rint1 () the { + father::p rint (); -cout <<"Weight:"<<weight; $ } $ intMain () - { -Son A ("Mike", the, the); the a.print1 (); -cout <<"it's over, \ n";Wuyi return 0; the}
Run results
Programme II
code example
1#include <iostream>2#include <string>3 using namespacestd;4 classFather5 {6 protected:7 stringname;8 inttall;9 Public:TenFatherstringAinti); OneFather () {cout <<"construct base class \ n"; } A voidPrint () {cout << name <<"height is"<< Tall <<"\ n"; } -~father () {cout <<"release base class object \ n"; } - }; the /*-------------is equivalent to the function of the original program-------------*/ -Father::father (stringAinti) - { -cout <<"\ n In the constructor of the base class \ n"; +Name =A; -Tall =i; + print (); Acout <<"leave the base class constructor \ n"; at } - classSon: PublicFather - { - Private: - intweight; - Public: inSonstringAintIintj); - voidprint1 (); to~son () {cout <<"\ nthe subclass object is released \ n"; } + }; - /*--------is equivalent to adding new functionality to the original program functionality-----------*/ theSon::son (stringAintIintJ): Father (A,i)//the Difference * { $ //name = A;Panax Notoginseng //tall = i; -cout <<"\ n in the subclass constructor \ n"; theWeight =J; + } A voidson::p rint1 () the { + father::p rint (); -cout <<"Weight:"<<weight; $ } $ intMain () - { -Son A ("Mike", the, the); the a.print1 (); -cout <<"it's over, \ n";Wuyi return 0; the}
Results show
Clearly, scenario two is better.
The role of inheritance and the method of initializing all the data in subclasses