Friend Operator< : How to Write?

Hello,

I've written a class that overloads the relational operator <.
I would like to make this into a friend function instead, how do i do this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Contact
{
    public:
        Contact();
        Contact(string, string);

        void setName(string, string);

        //Overloading operators
        bool operator==(const Contact &);

        bool operator<(const Contact &);
        bool operator>(const Contact &);
        bool operator!=(const Contact&);
        
        friend ostream &operator<<(ostream &output, const Contact& c)
        {
        	output << "Name: " << c.First << " " << c.Last << endl;
        	return output;
		}

    private:
        string First;
        string Last;

};

//Current Function Definition
 bool Contact::operator<(const Contact &c)
 {
	
 	if(Last < c.Last){
 		return true;
	 }
	 	
	if(Last == c.Last){
 		cout<<"last names same, lets check first < ... " << endl;
 		if(First < c.First)
 			return true;
	return true;	
 	} 
 	
	else
 		return false;
 }


would i do it like this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
friend bool &operator<(const Contact &c)
{
 	if(Last < c.Last){
 		return true;
	 }
	 	
	if(Last == c.Last){
 		cout<<"last names same, lets check first < ... " << endl;
 		if(First < c.First)
 			return true;
	return true;	
 	} 
 	
	else
 		return false;
}
Last edited on
No.

As initially written it is a member function of class Contact, which means that the b in
b < c
is actually the invoking class and you therefore only need one argument (which will be c).

If it is to be a separate function then it will have to have two arguments; declared something like
friend bool operator<( const Contact b, const Contact c );
within your Contact class, together with a function definition
1
2
3
4
bool operator<( const Contact b, const Contact c )
{
// function definition
}

outside. Note that (a) there are now two arguments; (b) there is no Contact:: preceding the definition.

The only reason it has to be a "friend" is to get at the private data members First and Last.

There is a much better explanation in Herbert Schildt's brilliant book on C++ programming.

Last edited on
Thank you, that really helps put it into context.
Topic archived. No new replies allowed.