Worksheet Answers: Classes

 

Rectangle.h:

   class Rectangle
   {
   public:
       void setlength(float);
       void setwidth(float);
       float perimeter();
       float area();
       void show();
   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;
   }

Client Code:

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

   int main()
   {
     Rectangle first;
     Rectangle second;

     first.setlength(5);
     first.setwidth(2.5);
     second.setlength(7.5);
     second.setlength(12.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;
     return 0;
   }


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

© Copyright Emmi Schatz 2006