Operator== overloading

As far as I have read. If I want to access a private member of a class, I should use friend. If I want to use find in <Algorithm>, I need to have operator==. But I have a problem is that what if I have to search different members? Suppose I have:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Log{
  public:
    Log(int user, int item, int re, int time);
    int getUser()  {return userID;}
    int getItem()  {return itemID;}
    int getTime()  {return timelog;}
    int getResult()  {return result;}
    friend bool operator== (const Log& log1, const int& member);
  private:
    int userID;
    int itemID;
    int timelog;
    int result;
};


I have different kind of private members. And if I use the operator== I declared this way:

1
2
3
bool operator== (const Log& log1, const int& member){
	return (log1.getUser() == member);
}


Then what should I do if I now want to find itemID or timelog? I have thought of declaring another one, but it would have the same variables as the one above. And it has the same variables, then how would I use them? I have read about same function name but different variable(s).
Last edited on
You'd have something like:

1
2
3
4
5
6
7
bool Log::operator==(const Log& other) const
{
    return userID == other.getUser() &&
           itemID == other.getItem() &&
           timelog == other.getTime() &&
           result == other.getResult();
}


No need for friend.
Oops. I declare getXXX() but I totally ignore it... Thanks!!
@iHutch105:
Your op== is a member of Log. A member has no need for get* -methods, because it has access to the privates.

tomtran3110's op== is a standalone function. Those indeed should make use of the (public) interface of the objects. Avoid making friends. They are (unnecessary) trouble.

Then what should I do if I now want to find itemID or timelog?

Indeed. You cannot differentiate by type, because all members are int.

The std::find_if accepts a predicate.
See http://www.cplusplus.com/reference/algorithm/find_if/

1
2
3
4
auto it = std::find_if ( logs.begin(), logs.end(),
                        []( const Log& log ) { return log.getUser() == 42; } );
auto jt = std::find_if ( logs.begin(), logs.end(),
                        []( const Log& log ) { return log.getItem() == 7; } );
Last edited on
Topic archived. No new replies allowed.