Construct a class named Rectangle that has double-precision data members named l
ID: 3575410 • Letter: C
Question
Construct a class named Rectangle that has double-precision data members named length and width. The class should have member (accessor) functions named double perimeter() and double area() to calculate a rectangle's perimeter and area, a member (mutator) function void setData (double, double) to set a rectangle's length and width, and a member (accessor) function void showData() that displays a rectangle's length, width, perimeter (using double perimeter()) and area (using double area()). b. Include the Rectangle class constructed in part a in a working C++ program.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