Example Code for Leak 6

 <  Free Open Study  >  

Example Code for Leak #6

 #include <iostream.h>  class Point {  int x, y;  char* color; public:  Point(int, int, char*);  Point(const Point&);  ~Point();  void print(); // Note the commented-out operator= //  const Point& operator=(const Point& rhs);  }; Point::Point(int new_x, int new_y, char* col) {  x = new_x; y = new_y;  color = new char[strlen(col)+1];  strcpy(color, col); } Point::Point(const Point& rhs) {  x = rhs.x; y = rhs.y;  color = new char[strlen(rhs.color)+1];  strcpy(color, rhs.color); Point::-Point()} {  delete color; } void Point::print() {  cout << ''I'm a point at ('';  cout << x <<'', '' << y << '')\n'';  cout << ''My color is '' <<color<<''.\n\n''; } // The following operation is a sample // implementation of the overloaded assignment // operator for the Point class. It is important that // the function allow for assignment of one object // to itself. The returned reference is marked // constant so that the return value of overloaded // operator= cannot be used as an lvalue. // That is, (x=y) = z is illegal. /* const Point& Point::opertor=(const Point& rhs) { // Avoid assignment to self.  if(this == &rhs) {   return(*this);  }  x = rhs.x; y = rhs.y;  delete color;  color = new char[strlen(rhs.color)+1];  strcpy(color, rhs.color);  return(*this); } */ main() {  Point p1(10, 10, ''Blue'');  Point p2(15, 18, ''Green");  p1.print(); p2.print();  p2=p1;  p1.print(); p2.print(); } 
 <  Free Open Study  >  


Object-Oriented Design Heuristics
Object-Oriented Design Heuristics (paperback)
ISBN: 0321774965
EAN: 2147483647
Year: 1996
Pages: 180

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net