************************************************************************ C++ ***
ID: 3674762 • Letter: #
Question
************************************************************************
C++
************************************************************************
Complete the Rectangle class.
class Rectangle
{
int length, width;
public:
...
};
Overload the +=, +, and << operators.
The += operator should add the int argument to both the length and width members.
The + operator should return the perimeter of the Rectangle.
The << operator should be written as a friend of the Rectangle class.
*************************************************************************
Use this main() as a test.
int main()
{
Rectangle R(7,3);
cout << R << " has perimeter " << +R << endl;
R += 5;
cout << R << " has perimeter " << +R << endl;
}
************************************************************************
It should produce the output:
Rectangle: length=7 width=3 has perimeter 20
Rectangle: length=12 width=8 has perimeter 40
Explanation / Answer
#include <iostream>
using namespace std;
class Rectangle
{
int length, width;
public:
Rectangle(){
length=0;
width=0;
}
Rectangle(float a, float b){
length = a;
width = b;
}
// Overload + operator to add two Box objects.
float operator+ ()
{
return 2*(this->length+this->width);//perimeter
}
// Overload += operator to add two Rectangle objects.
void operator+=(const int b)
{
this->length = this->length + b;
this->width = this->width + b;
}
// Overload + operator to add two Rectangle objects.
friend ostream &operator<<( ostream &output, const Rectangle &r )
{
output << "length : " << r.length << " Width : " << r.width;
return output;
}
};
int main()
{
Rectangle R(7,3);
cout << R << " has perimeter " << +R << endl;
R += 5;
cout << R << " has perimeter " << +R << endl;
}
/*
Output:
length : 7 Width : 3 has perimeter 20
length : 12 Width : 8 has perimeter 40
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.