The book I'm using continues to give me code and fails to explain the syntax. I got to a chapter on operator overloading and it gave me some code but didn't actually explain any of the code. I having trouble understanding the Rectangle operator+ line and that methods contents. Why does there need to be a constant? why is there an & symbol at the end of Rectangle in the argument list? What is the difference between width and p1.width? Thanks
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle()
{
width = 0;
height = 0;
}
Rectangle(int nx, int ny)
{
width = nx;
height = ny;
}
~Rectangle() {}
Rectangle operator+ (const Rectangle& p1)
{
return Rectangle(width + p1.width, height + p1.height);
}
int getWidth() { return width; }
int getHeight() { return height; }
private:
int width; // width of our rectangle
int height; // height of your rectangle
};
int main()
{
Rectangle ptA(1, 2); // create a 1x2 rec
Rectangle ptB(3, 4); // create a 3,4 rec
Rectangle ptC = ptA + ptB; // add them together
cout << "THe sum of RectangleA and RectangleB is:= (" << ptC.getWidth() << "," << ptC.getHeight() << ")" << endl;
return 0;
}