Plus operator

Trying to make a "+" operator to add two objects of a class but having difficulties please correct the code someone
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
52
53
54
55
  #include<iostream>

using namespace std;

class math
{
private:
	int value;

	
public:
	math()
	{
		value = 0;
	}


	void setvalue(int a)
	{

		value = a;
	}
	int getvalue()
	{
		cout << value<<endl;
		return value;

	}
	math grp(int value)
	{
		math b1;
		b1.value = value + 1;
		cout << b1.value;
		return b1;
	}
	math operator+(int c,int j)
	{
		math v1;
		v1 = c + j;
		cout << v1;
	}
};

void main()
{
	math a1,a2,a3;
	a1=a1.setvalue(3); 
	cout << endl;
	a1.getvalue();
	a2=a2.grp(25);
	cout << endl;
	a1.setvalue() + a1.getvalue();
	a3 = a1 + a2;
	cout << a3;
}
The operator should be declared as:
math & operator+(const int);

Then if your code says something like this:
1
2
3
math m, n;
m.setvalue(5);
n = m+3;

then line 3 is equivalent to:
n = m.operator+(3);
In other words, the compiler calls operator+() on the left operand, and passes the right operand as the argument.
would this little example help?

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
#include <iostream>

using namespace std;

class MyClass {
private:
    int value;
public:
    MyClass () {value = 0;};
    void print () {cout << "\n\tValue: " << value << endl;};
    MyClass operator+ (MyClass);
    MyClass (int a) {value = a;}
};

int main () {

    MyClass obj1(5), obj2(2);

    obj1.print ();
    obj2.print ();
    MyClass obj3 = obj1 + obj2;
    obj3.print ();
    return 0;
    }

MyClass MyClass::operator+ (MyClass param) {
    MyClass temp (value + param.value);

    return temp;
    }
Topic archived. No new replies allowed.