c++ - operator overloading "+" for types complex/double -


i put useful information in complex.cpp.

here problem: made class complex means can calculate in complex. in + operator want enable complex + double, can use complex + double in main.cpp. when use double variable + complex there error. why that? can fix it?

complex.h

#ifndef complex_h #define complex_h using namespace std; class complex { public:     complex( double = 0.0, double = 0.0 ); // constructor     complex operator+( const complex & ) const; // addition     complex operator-( const complex & ) const; // subtraction     complex operator*( const complex & ) const; // mul     bool operator==( const complex & ) const;     bool operator!=( const complex & ) const;     friend ostream &operator<<( ostream & , const complex& );      friend istream &operator>>( istream & , complex& );     complex operator+( const double & ) const;     //complex &operator+( const double & ) const;     void print() const; // output private:     double real; // real part     double imaginary; // imaginary part }; // end class complex  #endif 

complex.cpp

complex complex::operator+( const complex &operand2 ) const {     return complex( real + operand2.real,imaginary + operand2.imaginary ); } // end function operator+  complex complex::operator+(const double &operand2) const {     return complex( real + operand2 , this->imaginary ); } 

main.cpp

int main() { complex x; complex y( 4.3, 8.2 ); complex z( 3.3, 1.1 );      double ss = 5;     x = z + ss;     x = ss + z;//this syntax illegal  

in order allow class appear right hand operand, operator needs non-member. since (in case) needs access private members, have friend:

class complex {     // ...     friend complex operator+(double lhs, const complex & rhs); };  complex operator+(double lhs, const complex & rhs) {     return complex(lhs+rhs.real, rhs.imaginary); } 

alternatively, have member taking arguments other way round, , addition symmetric, define non-member, non-friend function:

complex operator+(double lhs, const complex& rhs) {     return rhs + lhs; } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -