No Viable Overloaded "="

Hi, even if I overload the operator =, I still get this error.

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
class Complex{
private:
	double re;
	double im;
public:
	Complex(){
		im=0.0;
		re=0.0;}
	~Complex(){};
	bool operator==(const Complex& right){
		if(re == right.re && im == right.im){
			return true;
		}
		else{
			return false;
		}
	}
	Complex* operator+(Complex& right){
		Complex* comp = 0;
		comp->re = right.re + re;
		comp->im = right.im + im;
		return comp;
	}
	Complex* operator-(Complex& right){
		Complex* comp = 0;
		comp->re = right.re - re;
		comp->im = right.im - im;
		return comp;
	}

	Complex* operator=(const Complex& right){
		Complex* comp = 0;
		comp->re = right.re;
		comp->im = right.im;
		return comp;
	}

#include <iostream>
#include "Complex.h"

int main(){
	Complex c1, c2, c3;
	c1.setRe(2.2);
	c1.setIm(2.2);
	c2.setRe(2.2);
	c2.setIm(2.2);
	if(c1 == c2){
	std::cout << "equals" << std::endl;
	}
	else{
		std::cout << "nope" << std::endl;
	}
    c3=c1+c2; //ERROR HERE

	return 0;
}


Thank you in advance
53 error: no match for ‘operator=’ (operand types are ‘Complex’ and ‘Complex*’)
your arithmetic operators return a pointer (¿?), not an object.


1
2
3
4
5
6
	Complex operator+(const Complex& right){
		Complex comp;
		comp.re = right.re + re;
		comp.im = right.im + im;
		return comp;
	}
You may provide `+=' and then code `+' in terms of it
1
2
3
4
5
6
7
8
Complex& Complex::operator+=(const Complex &right){ //as a member function
   this->re += right.re;
   this->im += right.im;
}

const Complex operator+(Complex a, const Complex &b){ //as a non-member function
   return a += b;
}
The return type of operator= needs to be a const Complex &

Then you do not need to create the Complex* comp - you actually want to be modifying the object on which the assignment operator is called, either by using the this pointer, or by simply putting re = right.re etc. inside the operator= function definition.

Finally you want to return a const reference to the current object - you do this by dereferencing the this pointer: return *this;

Also, your + and - operators should be returning a copy of a Complex object, not a pointer to a Complex object.

Hope this helps!
Thank you!
Topic archived. No new replies allowed.