Example: Define a class system that inherits and derives relationships, and access base class members in derived classes. First, define a point class that contains x, y coordinate data members, function members that display functions and calculated areas, derive a circle class from a point base class, add data members that represent radii, overload display and compute area functions, define a segment class, and define display, area, and length functions as data members with two point class objects. the segment class is aggregated because there are two endpoints and cannot be derived
The following notes are considerations
#include <iostream>#include<cmath>using namespacestd;Const floatPI =3.14; classPoint {Private: Doublex, y;intArea ; Public: Point (intXinty) { This->x =x;//You need to be aware that you must use the This keyword otherwise you cannot assign a value to x This->y =y;}; floatArea () {returnArea ;} FriendclassLine ;}; classCircle: PublicPoint {Private: floatR; Public: Circle (intXintYfloatr):P oint (x, y) {//Note the typical example of data initialization in this area This->r =R;} floatArea () {cout<< r*r*PI;return 0; } }; classLine {Private: Point A, B; Public: Line (): A (0,0), B (0,0) {} line (intAintBintCintD): A (A, b), B (c, D) {}intLong () {cout<<Endl;
//You need to note that a is an object in the line class but is extended by the point class, so you should use A.X (the variable in the Point Class) cout << sqrt ((a.x-b.x) * (A.X-B.Y) + (A.Y-B.Y) * ( a.y-b.y)); return 0;}}; int main () {Circle C (0, 0, 2); C.area (); Line Point (5,5,9,6); Point. Long (); return 0;}
About the Friend function function initialization