overloaded operators dependencies

Jan 15, 2011 at 3:05am
When you make a Class Class::operator+(Class a); function does it need an assignment operator overloaded to work?

I mean using A = B + C // all of the same classes ?


Also, when using my own code with an overloaded operator, gcc tells me "declaration of 'operator+' as non-function" and for my overloaded constructs... it's ambigious(the default one that is)

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

class Operate
{
	int ls, rs;
	public:
		Operate();
			//test: should make an error when compiling because of the dual default constructors
			//	test fail bcuz 
		Operate(int lhs = 0, int rhs = 0);
		Operate(int lhs, int rhs, char tMath );
		void print () {std::cout << ls << std::endl << rs << std::endl;}
		void set (int x, int y) { ls = x; rs = y; }
		Operate operator+ (Operate rhs);
};

Operate::Operate (int lhs , int rhs =)
{
	ls = lhs;
	rs=rhs;
}

Operate::Operate (int lhs, int rhs, char tMath)
{
	ls = lhs;
	rs=rhs;
	if ( tMath == '+')
	{
		ls + rs;
		std::cout << this.add() << std::endl;

		}else
			std::cout << "Error occured while initializing\n";
		
}
	
Operate Operate::operator+ (Operator rhs)
{
	Operate temp;
	temp.ls = ls +rhs.ls;
	temp.rs = rs +rhs.rs;
	return(temp);
}

int main ()
{

	Operate GG;
	Operate GGG( 20, 24);
	Operate GGGG(34, 244);

	GG = GGG + GGGG;
GG.print();

return 0;
}


it had much more errors, but I eliminated most by prob solve & eliminating useless code.

Last edited on Jan 15, 2011 at 3:07am
Jan 15, 2011 at 5:02am
No you don't. The default compiler generated one will work in this case since your member variables are just int. You will to write your own assignment operator in case that you need to do deep copy. It's still a good practice to write one yourself, however.
Topic archived. No new replies allowed.