Code the definition for the operator for the following clas
Code the definition for the = operator for the following class:
class Road
{
float length;
float width;
};
Road& operator=(Road& right)
{
length = right.length;
width = right.length;
}
Solution
#include <iostream>
using namespace std;
class Road
{
private:
float length;
float width;
public:
Road() //default constructor
{
length =0;
width =0;
}
Road(float length,float width) //parameterized constructor
{
this-> length = length;
this-> width = width;
}
Road& operator=(Road& right) //overloaded assignment operator
{
this->length = right.length;
this-> width = right.width;
}
void setLength(float length) //set and get methods for length and width
{
this->length = length;
}
float getLength()
{
return length;
}
void setWidth(float width)
{
this->width = width;
}
float getWidth()
{
return width;
}
};
int main()
{
Road R1,R2;
float length,width;
cout<<\"Enter the length and width of road 1\";
cin>>length>>width;
R1.setLength(length);
R1.setWidth(width);
cout<<\"\ Length of road 1 : \"<<R1.getLength();
cout<<\"\ Width of road 1 : \"<<R1.getWidth();
R2 = R1; //assigning R1 to R2;
cout<<\"\ Length of road 2 :\"<<R2.getLength(); //display R2
cout<<\"\ Width of road 2 :\"<<R2.getWidth();
return 0;
}
output:

