| < Day Day Up > |
|
The equality operators are used to compare the equality of two objects. Like the relational operators, the concept of equality is left to the discretion of the programmer. Example 14.10 gives the Person class extended to include both equality operators.
Listing 14.10: extended Person class
1 #ifndef __Person_H 2 #define __Person_H 3 #include <iostream> 4 #include <fstream> 5 using namespace std; 6 7 class Person{ 8 public: 9 Person(char* _f_name = "John", char* _m_name = "M", 10 char* _l_name = "Doe", char _sex = 'M', int _age = 18); 11 ~Person(); 12 Person(Person& person); 13 Person&operator=(Person& rhs); 14 void setFirstName(char* f_name); 15 void setMiddleName(char* m_name); 16 void setLastName(char* l_name); 17 void setAge(int age); 18 void setSex(char sex); 19 char* getFullName(); 20 char* getFirstName(); 21 char* getMiddleName(); 22 char* getLastName(); 23 char getSex(); 24 int getAge(); 25 friend ofstream& operator<<(ofstream& out, Person& p); 26 friend ifstream& operator>>(ifstream& in, Person& p); 27 friend ostream& operator<<(ostream& out, Person& p); 28 bool operator<(Person& rhs); 29 bool operator>(Person& rhs); 30 bool operator<=(Person& rhs); 31 bool operator>=(Person& rhs); 32 bool operator==(Person& rhs); 33 bool operator!=(Person& rhs); 34 private: 35 char* f_name; 36 char* l_name; 37 char* m_name; 38 char sex; 39 int age; 40 char* full_name; 41 bool name_changed; 42 }; 43 #endif
Example 10.11 gives the source code for the implementation of both operators.
Listing 14.11: equality operator implementation
1 bool Person::operator==(Person& rhs){ 2 return (this == (&rhs)); 3 } 4 5 bool Person::operator!=(Person& rhs){ 6 return (this != (&rhs)); 7 }
Notice how the implementation of these operators differ from the relational operators. I have made the choice here to compare the this pointer of the left hand side object to the address of the right hand side object. If the addresses are the same, they must be the same object, otherwise they are different objects. I could just as easily have chosen a class attribute, such as age, as I did for the relational operators, to make the comparison. Example 14.12 shows the equality operators in action.
Listing 14.12: main.cpp
1 #include <iostream> 2 using namespace std; 3 #include "person.h" 4 5 int main(){ 6 7 Person Rick("Rick", "Warren", "Miller", 'M', 41); 8 Person Bob("Bob", "J", "Jones", 'M', 25); 9 10 if(Rick == Rick) 11 cout<<"Same person!"<<endl; 12 else cout<<"Different person!"<<endl; 13 14 if(Rick != Bob) 15 cout<<"Different person!"<<endl; 16 else cout<<"Same person!"<<endl; 17 return 0; 18 }
Figure 14-6 shows the results of running example 14.12.
Figure 14-6: Results of Running Example 14.12
| < Day Day Up > |
|