Help with operator overloading

Hi,

I am in bit of a stump here. I am trying to get the parameters of a rectange (width and height) and with operator overloading create a function to have the rectangle parameter plus the this object parameters. When I type in the "this" I get the squiggly lines using Visual Studio 2010 Express.

Ex: return Rectangle(this.width + objWidth + this.hieght + objHeight);


What am I doing wrong?

Thanks


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>

using namespace std;

class Rectangle {

	double width;

	double height;

public:

	double area() 
	{
		return width * height;
	}

	void setHeight(double h) 
	{
		height = h;
	}

	void setWidth(double w) 
	{
		width = w;
	}

	double getHeight() 
	{
		return height;
	}

	double getWidth() 
	{
		return width;
	}

};

Rectangle operator+(const Rectangle &objWidth, const Rectangle &objHeight)
{
	return Rectangle(this.width + objWidth + this.hieght + objHeight);
};

int main()
{
	Rectangle Rectangle1;

	system("PAUSE");
	return 0;
}
Last edited on
1. this is a pointer, not a reference, so you would use -> instead of .
2. The function on line 40 is not a non-static member of a class, so there is no such thing as the this pointer for it.

You should rename your parameters to a and b so you understand what they mean.

How do you "add" rectangles in real life? Does it even make sense?
Last edited on
Thanks for your input, I solved it :)

This is how my class is, more focused on theory instead of logic. Makes it hard for me to understand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include "Rectangle.h"

using namespace std;

int main()
{
	//Set member variables to zero
	double width=0;
	double height=0;

	//Create 3 class Rectangle objects
	Rectangle Rectangle1;
	Rectangle Rectangle2;
	Rectangle Rectangle3;

	//Set width and Set height
	Rectangle1.setWidth(2);
	Rectangle1.setHeight(3);

	Rectangle2.setWidth(4);
	Rectangle2.setHeight(5);

	//Get width and Get height
	width = Rectangle1.getWidth();
	height = Rectangle1.getHeight();

	width = Rectangle2.getWidth();
	height = Rectangle2.getHeight();

	// Add two objects together
	Rectangle3 = Rectangle1 + Rectangle2;

	cout << "The number is " << Rectangle3.getWidth() + Rectangle3.getHeight() << endl;

	system("PAUSE");
	return 0;
}
Topic archived. No new replies allowed.