#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
const is only for member functions, not global functions.
Your Complex operator +(constdouble& d, const Complex& z) doesn't need to use const to guarantee that it doesn't change the object it's part of... because it's not part of an object.
constint function1(); // this is how you return a const
int function2() const;
// here const says that function2 cannot change contents of the object it's part of
// function2 must be part of a class, and not be a global function
You can return a const but it doesn't make sense to do so for local variables inside that function.