// This file contains a class called coordinate. It has two member // variables x and y. It defines two constructors for the class, one // that accepts no parameters and one that accepts two parameters. // Note that only the one that accepts parameters is actually used in // this example. // // The class also has a number of operators defined. Note how they // are defined and how they are used. #include #include #include #include class coordinate { private: int x; int y; public: // This constructor expects no parameters. // It uses default values for x and y. coordinate(void); // This one is used when the initial values for x and y are specified // by the user. coordinate(int xval, int yval); int xvalue(void); int yvalue(void); void print(char *pstring); void operator =(coordinate& C); void operator +=(coordinate& C); void operator -=(coordinate& C); int operator ==(coordinate& C); coordinate operator +(coordinate& C); coordinate operator -(coordinate& C); }; // This constuctor accepts no parameters and initializes x and y to 0. coordinate::coordinate(void) { x = 0; y = 0; } // This constructor accepts initial values for x and y coordinate::coordinate(int xval, int yval) { x = xval; y = yval; } // print() prints out the values of x and y void coordinate::print(char *pstring) { cout << pstring << ": coordinates: x = " << x << ", y = " << y << "\n"; } // xvalue() returns the value of x int coordinate::xvalue(void) { return(x); } // yvalue() returns the value of y int coordinate::yvalue(void) { return(y); } // This defines the = operator for the coordinate class void coordinate::operator =(coordinate& C) { x = C.xvalue(); y = C.yvalue(); } // This defines the += operator for the coordinate class void coordinate::operator +=(coordinate& C) { x += C.xvalue(); y += C.yvalue(); } // This defines the -= operator for the coordinate class void coordinate::operator -=(coordinate& C) { x -= C.xvalue(); y -= C.yvalue(); } // This defines the + operator for the coordinate class coordinate coordinate::operator +(coordinate& C) { coordinate D(x + C.xvalue(), y + C.yvalue()); return(D); } // This defines the - operator for the coordinate class coordinate coordinate::operator -(coordinate& C) { coordinate D(x - C.xvalue(), y - C.yvalue()); return(D); } // This defines the == operator for the coordinate class int coordinate::operator ==(coordinate& C) { return( (x == C.xvalue()) && (y == C.yvalue()) ); } // This program just tests out the operators we have defined // for the coordinate class. main() { coordinate A(5, 10), B(3, 7), C(20, 30); A.print("A"); B.print("B"); C.print("C"); cout << "\n--1--\n"; A += C; A.print("A"); cout << "\n--2--\n"; A = B; A.print("A"); cout << "\n--3--\n"; A = B + C; A.print("A"); cout << "Hit a key to exit"; getch(); }