overloading

why this code won't work?
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
#include<iostream>

//=============== Complex ============================
class Complex {

	friend Complex operator +(const double& d, const Complex& z) const;					// return const 

private:
	double _r,_i;

public:
	Complex():_r(0),_i(0){}
	Complex(int r,int i):_r(r),_i(i){}

};

//============== Global Functions ===============================
Complex operator +(const double& d, const Complex& z) const {	// he have access for private parameters because of friend declaration
	return Complex(z._r+d,z._i);
}


// =========================== Main Functions ============================================
void foo(){
	Complex z1(1,1),z2,z3;
	z2 = 1 + z1;							// 1
}
// =========================== Main ============================================
int main(){
	foo();

return 0;
}


while this is working good:
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
#include<iostream>

//=============== Complex ============================
class Complex {

	friend Complex operator +(const double& d, const Complex& z) ;					// return non const 

private:
	double _r,_i;

public:
	Complex():_r(0),_i(0){}
	Complex(int r,int i):_r(r),_i(i){}

};

//============== Global Functions ===============================
Complex operator +(const double& d, const Complex& z)  {	// he have access for private parameters because of friend declaration
	return Complex(z._r+d,z._i);
}


// =========================== Main Functions ============================================
void foo(){
	Complex z1(1,1),z2,z3;
	z2 = 1 + z1;							// 1
}
// =========================== Main ============================================
int main(){
	foo();

return 0;
}


when I compile the first code I get:
overloading.cpp:6: error: non-member function ‘Complex operator+(const double&, const Complex&)’ cannot have cv-qualifier
overloading.cpp:20: error: non-member function ‘Complex operator+(const double&, const Complex&)’ cannot have cv-qualifier

Read the error carefully
In your case operator+ is a global function. If you want the returned value to be constant, the prototype should be
const Complex operator+( //...
Topic archived. No new replies allowed.