DrkDeveloper
DrkDeveloper

Reputation: 949

operator= in c++ (11) working direction

I'm doing a Little rational class for my Project and I overload all aritmethic operators. Well, when I try to overload operator= I have a Little and now I don't know if is my problem (i don't know how it Works) or problem of my wroten code (i wrote it bad) here's the 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 that all is wrong haha)

My goal is do that:

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

Can I do it? if yes, how?

Upvotes: 1

Views: 308

Answers (2)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

Here I think a user-defined conversion operator would be more appropriate.

class rational {
public: 
    rational( int iNum, int iDen ) : num( iNum ), den( iDen ) {}

    // ... 
    operator double() { return (double)num / (double)den; }

private: 
    int num;
    int den;
};

int main()
{
    rational r( 1, 2 );
    double n = r;

    std::cout << r << std::endl; // output 0.5
    return 0;
}

Here is a little live example to illustrate this : http://ideone.com/I0Oj66


About the copy assignment operator= :

A copy assignment operator of class T is a non-template non-static member function with the name operator= that takes exactly one parameter of type T.

The operator= is used to change an existing object.

You can use it for example to copy the state of another object :

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

Upvotes: 2

sfjac
sfjac

Reputation: 7284

You don't want an assignment operator for this purpose - you should instead overload a conversion operator; e.g.

class rational {
  private: 
    int num;
    int den; 

  public: 
    // ... 
    operator double() { return double(num) / double(den); }
};

This will allow

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

The assignment operators should be used for changing the state of an existing object, if that's something you want to allow. You probably would not want to allow assignment of a double to a rational there is no unambiguous meaning for such an operation. However, you might want to provide helpers for assigning an int, say, in addition to the usual one for assigning another rational:

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

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

Upvotes: 3

Related Questions