Question

This is the first time I've tried overloading in c++ (Still learning, of course) and I'm not quite sure why this code is erroring?

bool operator<= (Vector3 v) {
    if (x <= v.x) && (y <= v.y) && (z <= v.z) {
        return true;
    }
}

The errors are

19|error: expected identifier before '(' token|

and

19|error: expected ';' before '(' token|

I searched for both of these and found that the first one is for code outside of a function (which it's not), but didn't find anything on the second.

Thanks for reading

Was it helpful?

Solution

The logic of the operator aside, you seem to be missing a set of parentheses in the if. This would by syntactically correct:

if ( (x <= v.x) && (y <= v.y) && (z <= v.z) )

But what you really should do is simplify the whole thing and avoid the unnecessary if:

bool operator<= (Vector3 v) {
    return (x <= v.x) && (y <= v.y) && (z <= v.z);
}

Finally, a comparison member function should be const, because it does not make sense to modify something while comparing it. Also, you may want to pass the argument by reference, although that depends on the size of Vector and on the cost to copy it.

bool operator<= (const Vector3& v) const
{
    return (x <= v.x) && (y <= v.y) && (z <= v.z);
}

OTHER TIPS

also adding to other answers, what would your statement return if not true, c++ doesn't return anything by default, that is why is better to return the operation result

return (x <= v.x) && (y <= v.y) && (z <= v.z);

The condition in the if statement shall be enclosed in parentheses. So the valid if statement will look as

if ( (x <= v.x) && (y <= v.y) && (z <= v.z) ) {

Also it would be better to defined the operator the following way

bool operator <=( const Vector3 &v ) const 
{
    return ( ( x <= v.x ) && ( y <= v.y ) && ( z <= v.z ) );
}

Note: You might consider this:

inline bool operator<= (const3 Vector& u, const Vector3& v) {
    if(u.x < v.x) return true;
    if(u.x == v.x) {
       if(u.y < v.y) return true;
       if(u.y == v.y) {
          if(u.z <= v.z) return true;
       }
    }
    return false;
}

Here you have a freestanding binary function, which takes the arguments by constant references to avoid needless copies. Also the logic is changed (x has a higher rank than y and y a higher rank than z). This makes [1, 1, 1] less than [1, 1, 2] (which is not the case in your logic).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top