-sharpinclude <iostream>
using namespace std;
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
void setLength(double len)
{
length = len;
}
void setBreadth(double bre)
{
breadth = bre;
}
void setHeight(double hei)
{
height = hei;
}
// + Box
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; //
double breadth; //
double height; //
};
//
int main()
{
Box Box1; // Box1 Box
Box Box2; // Box2 Box
Box Box3; // Box3 Box
double volume = 0.0; //
// Box1
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// Box2
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// Box1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume << endl;
// Box2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume << endl;
// Box3
Box3 = Box1 + Box2;
// Box3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume << endl;
return 0;
}
where overloaded operator function:
// + Box
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
The parameter in has a const Box& b, and what"s the use of &? I can run normally if I remove it. It doesn"t mean to take the address of the variable, is it? I can"t figure it out
and there is only one parameter here, but the Box itself also participates in running
Box3 = Box1 + Box2;
during the operation. Does the binary operator have a default parameter of itself, but you can write other parameters without writing it? add up the
three:
Box4 = Box1 + Box2 + Box3;. Should
be written like this:
Update: it is wrong to write the following. It has been tried. The + operator has at most one parameter. If the three operators add up, you should still use the above method. Just write the three additions on the outside
Box operator+(const Box& b,const Box& c)
{
Box box;
box.length = this->length + b.length + c.length;
box.breadth = this->breadth + b.breadth + c.breadth;
box.height = this->height + b.height + c.height ;
return box;
}
Thank you