Overloading paramenters

I have to overload parameters and I started with the "<" parameter to compare two classes together. I have this as my code but it keeps saying that the function bool Money :: operator<(const Money &, const Money&) must take exactly one argument. Why can't I pass both? is there a more efficient way of doing this?
There are values already in both classes. If anyone can steer me the right direction. Thanks



1
2
3
4
5
6
7
8
9
10
bool Money::operator<(const Money &m,const Money &d)
{

    int a = m.getValue();
    int b = d.getValue();
    cout << a << b << endl; /// debugging
    return a < b;

}
Two options:

1) Make this operator global so it takes 2 params.

or

2) Get rid of the 'm' parameter. When the operator is a member, you use 'this' as the left-hand side of the operator:

1
2
3
4
5
6
7
8
9
10
11
12
// option 1
bool operator<(const Money &m,const Money &d) // <- global
{
    return m.getValue() < d.getValue();
}


// option 2
bool Money::operator < (const Money& d)
{
    return getValue() < d.getValue();
}

I changed the function to your suggested option 2, since I have to make it a class function.

However, I received the following error.

"error: passing 'const Money as 'this' argument of 'int Money::getValue()' discards qualifiers"

Edit*

Once I took the "const" out of the parameter it worked... Thanks!
Last edited on
If you have a const object, you can only call const functions (since non-const functions might modify the state of that object).

If getValue is a non-const function, then you won't be able to call it from your < operator. You'll need to make it const:

1
2
3
4
5
6
7
int Money::getValue() const  // <- note the 'const' keyword
{
   // ... 
}

bool Money::operator < (const Money& d) const // <- also do that with the < operator, too
   // I messed up and forgot about it before.  Whoops. 
closed account (48T7M4Gy)
Check out the use of 'friend'. It allows your overloaded operator to accomodate 2 arguments and access to their private parts, no pun intended.
closed account (48T7M4Gy)
http://www.learncpp.com/cpp-tutorial/96-overloading-operators-using-member-functions/
Topic archived. No new replies allowed.