function - overloading operator * c++ -


i have been trying compile program giving me error in regards overloading * operator 1 of functions: complex operator *(double n)const

when try compile error: no match 'operator*' in '2 * c'

here header file:

complex.h

#ifndef complex0_h #define complex0_h  class complex {     double realnum;     double imagnum; public:     complex();     complex(double x,double y);     complex operator *(double n)const;     complex operator *(const complex &c1)const;    friend std::istream &operator>>(std::istream &is,complex &cm);    friend std::ostream &operator<<(std::ostream &os,const complex &cm); };  #endif 

here cpp:

complex.cpp

 #include "iostream" #include "complex0.h"  complex::complex() {     imagnum = 0.0;     realnum = 0.0; }  complex::complex(double x, double y) {      realnum = x;     imagnum = y; }  complex complex::operator *(const complex& c1) const{ complex sum; sum.realnum=realnum*c1.realnum-c1.imagnum*imagnum; sum.imagnum=realnum*c1.imagnum+imagnum*c1.realnum;     return sum; }  complex complex::operator *(double n)const{      complex sum;     sum.realnum=realnum*n;     sum.imagnum=imagnum*n;     return sum;  } std::istream &operator >>(std::istream& is, complex& cm) {     >> cm.realnum>> cm.imagnum;     return is; }  std::ostream &operator <<(std::ostream& os, const complex& cm){ os<<"("<<cm.realnum<<","<<cm.imagnum<<"i)"<<"\n";     return os; } 

main.cpp

#include <iostream> using namespace std; #include "complex0.h"       int main() {         complex a(3.0, 4.0);          complex c;         cout << "enter complex number (q quit):\n";         while (cin >> c) {             cout << "c " << c << "\n";             cout << "a " << << "\n";             cout << "a * c" << * c << "\n";             cout << "2 * c" << 2 * c << "\n";             cout << "enter complex number (q quit):\n";         }         cout << "done!\n";         return 0;     } 

can explain me have done wrong?

the member function operator applies when first operand of class type. if want handle case second operand of type, need free function (in delegate member function virtue of commutativity of operation):

complex operator*(double n, complex const & x) {     return x * n; } 

(please note standard library contains <complex>.)


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -