#include<iostream>
//=============== Complex ============================
class Complex {
friend Complex operator +(constdouble& 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 +(constdouble& 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+( //...