How to compare Class struct

Okay so obviously I know my if statement is wrong, I was just trying to guess before posting here. The goal of this program is to print the default numbers, then have the user enter 2 phone numbers and then compare them, printing equal or not equal. What I can't figure out is how to make the comparison because the class is made up of integers and a string.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <string>
using namespace std;

	struct Phone
	{
	private:
		int country;
		int area;
		int number;
		string type;
	public:
		Phone();
		void setPhone();
		void getPhone();
	};

int main()
{
	Phone num1;
	Phone num2;


	num1.getPhone(); //prints default number 0-0-0 HOME
	num2.getPhone();
	
	cout<<endl;
	num1.setPhone();
	cout<<endl;
	num2.setPhone();
	cout<<endl;

	num1.getPhone();
	num2.getPhone();

	/*if(num1.getPhone()==num2.getPhone())
	{
		cout<<"Numbers are equal"<<endl;
	}
	else
	{
		cout<<"Numbers are not equal"<<endl;
	}*/

	cout<<endl;
	
	return 0;
}

Phone::Phone()
{
	country = 000;
	area = 000;
	number = 0000000;
	type = "HOME";
}

void Phone::setPhone()
{
	cout<<"Enter the country code"<<endl;
	cin>>country;
	cout<<"Enter the area code"<<endl;
	cin>>area;
	cout<<"Enter the phone number"<<endl;
	cin>>number;
	cout<<"Enter the type of phone number you are calling (HOME, OFFICE, FAX, CELL, or PAGER)"<<endl;
	cin>>type;
}

void Phone::getPhone()
{
	cout<<country<<"-"<<area<<"-"<<number<<" "<<type<<endl;
}
you can have a member function that accepts another Phone object
and compares them respectively, something like :
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Phone
{
    // ...
public :
    bool equals( const Phone& other ) { // Java-like
        return country == other.country &&
               area    == other.area    &&
               number  == other.number  &&
               type    == other.type;
    }
    // ...
};
// if( num1.equals(num2) ) { } 

Or you can use operator overloading so you can compare
two Phone objects by simply using ==.
like: if( object1 == object2 ) { }
1
2
3
4
5
6
7
8
9
10
11
12
13
struct Phone
{
    // ...
public :
    bool operator==( const Phone& other ) {
        return country == other.country &&
               area    == other.area    &&
               number  == other.number  &&
               type    == other.type;
    }
    // ...
};
// now, you can simply use : if( num1 == num2 ) 
Last edited on
Thank you!
Topic archived. No new replies allowed.