// --------------------------- // rect.cpp // --------------------------- #include #include class rect { public: // access specifier rect(double x1i,double x2i, double y1i, double y2i); rect(const rect &ri); // copy constructor rect &operator =(rect &ri); // assignment operator ~rect() {} // destructor [ not really needed here ] double area(); void move(double dx, double dy); friend void p(rect &r); friend void pl(rect &r); private: double x1,x2,y1,y2; }; rect::rect(double x1i,double x2i, double y1i, double y2i): x1(x1i),x2(x2i),y1(y1i),y2(y2i) {} rect::rect(const rect &ri): x1(ri.x1), x2(ri.x2),y1(ri.y1),y2(ri.y2) {} rect &rect::operator =(rect &ri) { x1 = ri.x1; x2 = ri.x2; y1 = ri.y1; y2 = ri.y2; return *this; } void rect::move(double dx, double dy) { x1 += dx; x2 += dx; y1 += dy; y2 += dy; } double rect::area() { return (x2-x1)*(y2-y1); } // ---------------------------------------- // some constants const double Pi = 3.1415926535897932; const double Exp1 = 2.7182818284590452; // ---------------------------------------- // print and new line for strings void nl() { cout << "\n"; cout.flush(); // apply nl right now cout << " "; // left margin } void p(char *s) { cout << s; } void pl(char *s) { p(s); nl(); } void p(char *s, double x) { p(s); cout << x; } void pl(char *s, double x) { p(s,x); nl(); } // ---------------------------------------- // print for rect void p(rect &r) { p("(",r.x1); p(",",r.x2); p(",",r.y1); p(",",r.y2); p(")"); } void pl(rect &r) { p(r); nl(); } // ---------------------------------------------------- void main() { nl(); // first left margin pl("------------- "); pl(" rect.cpp "); pl("------------- "); rect r(Pi,5*Pi,Exp1,Pi); // constructor p("r = "); pl(r); pl("area of r = ", r.area()); nl(); r.move(1,2); rect r1(r); // copy constructor p("r1 = "); pl(r1); pl("area of r1 = ", r1.area()); nl(); r1.move(-1,-2); rect r2 = r1; // assignment operator r = r2 = r1; // this is alright p("r = "); p(r); pl(" = r2 ="); p(" = "); pl(r2); pl("area of r2 = ", r2.area()); } /* output ------------- rect.cpp ------------- r = (3.14159,15.708,2.71828,3.14159) area of r = 5.31948 r1 = (4.14159,16.708,4.71828,5.14159) area of r1 = 5.31948 r = (3.14159,15.708,2.71828,3.14159) = r2 = = (3.14159,15.708,2.71828,3.14159) area of r2 = 5.31948 */