The following questions refer to the rectangle class Rect declaration in the hea
ID: 3789526 • Letter: T
Question
The following questions refer to the rectangle class Rect declaration in the header file:
class Rect {
public:
Rect(int len, int wid);
int GetArea();// return the area of the rectangle
// space for adding new member functions
private:
int length;
int width;
};
1) Define the constructor Rect(int len, int wid); in the implementation file.
2) Write the implementation for member function int GetArea()
3) Declare and implement a new method (function member) bool isItASquare() to check if the Rect object is a square.
4) Declare and implement a new method (function member) void display(ostream & out) const so that it can be used to print a Rect object in the format [length, width]. For example:
Rect r(5, 3);
r.display(cout); // it should print the Rect r as [5, 3]on the screen.
Explanation / Answer
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
class Rect {
public:
Rect(int len, int wid);
int GetArea();// return the area of the rectangle
bool isItASquare();
void display(ostream & out);
// space for adding new member functions
private:
int length;
int width;
};
Rect::Rect(int len, int wid){
length = len;
width = wid;
}
int Rect::GetArea(){
return length * width;
}
bool Rect::isItASquare(){
if(length == width){
return true;
}
else{
return false;
}
}
void Rect::display(ostream & out){
out<<"[ "<<length<<","<<width<<" ]"<<endl;
}
int main()
{
Rect r(5, 3);
r.display(cout);
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
[ 5,3 ]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.