c++ operator overloading, division

I need to create an overloaded operator / that will divide a number by n.

how would I do that if

example(0, 5, 0)
cout << example << " divided by 2 is " << example/2 << endl;
?

is there a way to put the number 2 (n) in to the definition below?

Myclass operator/(const Myclass& one, const Myclass& two)
{
?
}
There are a few options. The easiest would be to define another overload of operator/ for an int, like so:
1
2
3
4
5
6
7
Myclass operator/ (const Myclass& left, int num) {
    //divide by num
}

Myclass operator/ (int num, const Myclass& right) {
    return (right / num); // call the first one
}


The other way would be to define an implicit constructor for Myclass that takes an integer, and the compiler would automatically create an instance of Myclass from an int to pass to the operator:
1
2
3
Myclass::Myclass(int num) {
    /* set the class based off num */
}


Which one you do is based on what your class is supposed to be doing. Generally, I prefer the second option, but from your example it looks like the first one is the way to go.
Last edited on
Topic archived. No new replies allowed.