int operator%( double a, double b ){
	int aa = (int) a;
	int bb = (int) b;
return aa%bb;
}

gives me an error message "must have an argument of class or enumerated type"!

As you can see, I want a simple program which truncates doubles into their equivalent integers, then performs the modular function on them.

It seems that if I change the function so that it is not an operator function,

int mod( double a, double b )

then it works just fine. So what's wrong with overloading the operator?

You are not allowed to overload an operator for a built-in type (int, float, double, char, etc.). So, if your operator overload only involves built-in types, even if that operator doesn't exist yet for that type, it is illegal to do so. This is just a safe-guard built into C++ to stop people from doing crazy things like redefining existing operators and giving them different semantics (and also, for technical reasons, such as overload resolution when built-in types don't reside in any namespace).

Just use a regular function with a name. Operator overloading is just syntactic sugar, don't abuse the feature, use it only when it fits very naturally and when the semantics are either completely analog to the "normal" use of the operator or when it is idiomatic (as in the << operator for ostreams in C++).

Thanks! It seems that only certain symbols (such as ~ and +=) can be used as operators. What if I wanted something else as an operator? Is it possible?

Alternatively, what if instead of using fun(a,b), I wanted to use a.fun(b). Is this also possible?

You can only overload an operator that is defined in c++. You cant make a # operator that swaps 2 numbers for example. As for third question if a is a user defined type you can do such a thing. In fact overloading an operator does just that. Take this for example.

class foo
{
    int bar;
    foo & operator=(const foo &);
};

foo & foo::operator=(const foo & foobar)
{
    bar = foobar.bar;
    return *this;
}

int main()
{
    //...
    foo a,b;
    a.bar = 5;
    // now assign a to b
    b = a;
    // or you could write it like
    b.operator=(a);
    // it is the same thing its just the first version is easier to read
    //...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.