Include the Rectangle class constructed in part a in a working C++ program. PART
ID: 3575393 • Letter: I
Question
Include the Rectangle class constructed in part a in a working C++ program. PARTIAL SOLUTION: #include stdafx.h // needed for MS C++ Express users #include using namespace std; class Rectangle // declaration section { private: double length, width; public: Rectangle(double len = 0, double wid = 0) // inline constructor {length = len; width = wid;} double perimeter() {return (2*length) + (2*width);} double area(); // accessor void setData(double len, double wid) void showData(); // accessor displaying rectangle info }; //implementation section double Rectangle::area() // accessor { return(length*width); } // include an implementation of void showData() accessor function here int main() { Rectangle a, b, c(3.0, 4.5); // declare three objects b.setData(2.0, 3.0); a.showData(); b.showData(); c.showData(); cin.ignore(); // needed for MS C++ Express users return 0; }Explanation / Answer
#include <iostream>
using namespace std;
class Rectangle{
private:
double length;
double width;
public:
Rectangle(double len=0, double w=0){
length = len;
width = w;
}
void setData(double l, double w){
length = l;
width= w;
}
double area();
double perimeter(){
return 2 * (width + length);
}
void showData();
};
double Rectangle::area(){
return width * length;
}
void Rectangle::showData(){
cout<<"Length: "<<length<<" Width: "<<width<<endl;
cout<<"Area: "<<area()<<" Perimeter: "<<perimeter()<<endl;
}
int main()
{
Rectangle a,b,c(3.0, 4.5);
b.setData(2.0,3.0);
a.showData();
b.showData();
c.showData();
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Length: 0 Width: 0
Area: 0 Perimeter: 0
Length: 2 Width: 3
Area: 6 Perimeter: 10
Length: 3 Width: 4.5
Area: 13.5 Perimeter: 15