locked
Why can I overload '+' but not '/'? RRS feed

  • Question

  • it says expected overloadable unary operator

    I've googled and read the msdn but it seems binary operators can be overloaded too. Yet  I get this error for

    public three_vector operator/( double a) 
    {
    	three_vector b;
    	b._x = _x/a;
    	b._y = _y/a;
    	b._z = _z/a;
    	return b;
    }

    and

    public three_vector operator+=( three_vector a)
    {
    	_x += a.x();
    	_y += a.y();
    	_z += a.z();
    	return *this;
    }

    and

    public double operator|(three_vector a) 
    {
    	return (_x*a.x() + _y*a.y() + _z*a.z());
    }

    but + is okay (it is in the list of unary operators)

    public three_vector operator+(  three_vector a) 
    {
    	three_vector b;
    	b._x = _x + a.x();
    	b._y = _y + a.y();
    	b._z = _z + a.z();
    	return b;
    }

    Thursday, September 13, 2012 8:33 PM

Answers

  • A unary operator is one that works on just a single argument. For example, the + operator that you have overloaded is this one...

    double x = +5.0;  // As opposed to -5.0.

    ... not this one...

    double x = 5.0 + 3.0; // This operates on two arguments, the 5 and the 3.

    All of the operators that you are trying to overload need two arguments, not one. For example, the + operator that you want (the additive one) should be like this...

    public static three_vector operator+( three_vector a, three_vector b) 
    {
    	three_vector c = new three_vector();
    	c._x = b.x() + a.x();
    	c._y = b.y() + a.y();
    	c._z = b.z() + a.z();
    	return c;
    }


    • Edited by Ante Meridian Friday, September 14, 2012 1:27 AM Forgot to make the example static.
    • Proposed as answer by servy42 Friday, September 14, 2012 2:43 PM
    • Marked as answer by s_b1 Friday, September 14, 2012 6:04 PM
    Friday, September 14, 2012 1:08 AM

All replies

  • A unary operator is one that works on just a single argument. For example, the + operator that you have overloaded is this one...

    double x = +5.0;  // As opposed to -5.0.

    ... not this one...

    double x = 5.0 + 3.0; // This operates on two arguments, the 5 and the 3.

    All of the operators that you are trying to overload need two arguments, not one. For example, the + operator that you want (the additive one) should be like this...

    public static three_vector operator+( three_vector a, three_vector b) 
    {
    	three_vector c = new three_vector();
    	c._x = b.x() + a.x();
    	c._y = b.y() + a.y();
    	c._z = b.z() + a.z();
    	return c;
    }


    • Edited by Ante Meridian Friday, September 14, 2012 1:27 AM Forgot to make the example static.
    • Proposed as answer by servy42 Friday, September 14, 2012 2:43 PM
    • Marked as answer by s_b1 Friday, September 14, 2012 6:04 PM
    Friday, September 14, 2012 1:08 AM
  • thank you, Ante!
    Friday, September 14, 2012 6:04 PM