Worksheet Answers: Classes

 

Rectangle.h:

   class Rectangle
   {
   public:
       Rectangle() { length = 1; width = 1; }
       Rectangle(float len,float wid) { length = len; width = wid; }
       void setlength(float);
       void setwidth(float);
       float perimeter();
       float area();
       void show();
       int sameArea(Rectangle);
   private:
       float length;
       float width;
   };

Rectangle.C:

   #include <iostream.h>
   #include "Rectangle.h"

   void Rectangle::setlength(float len)
   {
       length = len;
   }

   void Rectangle::setwidth(float wid)
   {
       width = wid;
   }

   float Rectangle::perimeter()
   {
       return 2 * length + 2 * width;
   }

   float Rectangle::area()
   {
       return length * width;
   }

   void Rectangle::show()
   {
       cout << "Length: " << length << "   Width: " << width;
   }

   int Rectangle::sameArea(Rectangle other)
   {
       float areainv = length * width;
       float areaparm = other.length * other.width;
       if (areainv == areaparm)
           return 1;
       return 0;
   }

//  alternate version of sameArea:
//   int Rectangle::sameArea(Rectangle other)
//   {
//       if (area() == other.area())
//           return 1;
//       return 0;
//   }


Client Code:

   #include <iostream.h>
   #include "Rectangle.h"

   int main()
   {
      Rectangle first;
      Rectangle second(4,3);

      cout << "First rectangle:  ";
      first.show();
      cout << endl << "Area: " << first.area() << "Perimeter: "
                               << first.perimeter() << endl << endl;
      cout << "Second rectangle:  ";
      second.show();
      cout << endl << "Area: " << second.area() << "Perimeter: "
                               << second.perimeter() << endl << endl;
      if (first.sameArea(second))
         cout << "Rectangles have the same area\n";
      else
         cout << "Rectangles do not have the same area\n";

      first.setlength(2);
      first.setwidth(6);

      cout << "First rectangle:  ";
      first.show();
      cout << endl << "Area: " << first.area() << "Perimeter: "
                               << first.perimeter() << endl << endl;
      cout << "Second rectangle:  ";
      second.show();
      cout << endl << "Area: " << second.area() << "Perimeter: "
                               << second.perimeter() << endl << endl;
      if (first.sameArea(second))
         cout << "Rectangles have the same area\n";
      else
         cout << "Rectangles do not have the same area\n";


     return 0;
   }


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2006