c++11 - operator= in c++ (11) working direction -


i'm doing little rational class project , overload aritmethic operators. well, when try overload operator= have little , don't know if problem (i don't know how works) or problem of wroten code (i wrote bad) here's code:

class rational{     public:       double& operator=(double& d){          d= this->num/this->den;          return d;       }       double& operator=(rational& r){             double d= r.num/r.den;             return d;       }       double& operator=(){             double d= this->num/this->den;             return d;       } } 

ok, what's wrong? what's right? (i think wrong haha)

my goal that:

int main(){     rational r(4, 5);     double d= r; } 

can it? if yes, how?

you don't want assignment operator purpose - should instead overload conversion operator; e.g.

class rational {   private:      int num;     int den;     public:      // ...      operator double() { return double(num) / double(den); } }; 

this allow

rational r(4, 5); double d = double(r); // d = 0.8  

the assignment operators should used changing state of existing object, if that's want allow. not want allow assignment of double rational there no unambiguous meaning such operation. however, might want provide helpers assigning int, say, in addition usual 1 assigning rational:

rational &operator=(const rational &rhs) {     num = rhs.num;     den = rhs.den;     return *this; }  rational &operator=(int rhs) {     num = rhs;     den = 1;     return *this; } 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -