Operator overload

I am wondering how to correctly use overloading operator in this example. I want to set Mary == Susan.
#include <iostream>
#include <string>

using namespace std;

struct student_record
{
	string firstname, lastname;
	double age, income;
	int number_of_children;
	char sex;
};

int main()
{

	student_record Mary;
	student_record Susan;

	cout<<"Enter the firstname and lastname: ";
	cin>>Mary.firstname;
	cin>>Mary.lastname;
	cout<<"Enter age: ";
	cin>>Mary.age;
	cout<<"Enter income: ";
	cin>>Mary.income;
	cout<<"Enter number of children: ";
	cin>>Mary.number_of_children;
	cout<<"Enter sex: ";
	cin>>Mary.sex;
	
	Susan = Mary;

	if (Susan == Mary)
	{
		cout<<Susan.firstname<<"    "<<Mary.lastname<<endl;
		cout<<Susan.age<<endl;
		cout<<Susan.income<<endl;
		cout<<Susan.number_of_children<<endl;
		cout<<Susan.sex<<endl;
	}
	return 0;
}
bool operator=(const student_record &a, const student_record &b)
{
    return a.firstname =b.firstname;
}

Last edited on
1
2
3
4
bool operator=(const student_record &a, const student_record &b)
{
    return a.firstname < b.firstname;
}
1) = and == are not the same.
2) if it is == why are you returning <?

1
2
3
4
bool operator==(const student_record &a, const student_record &b)
{
    return a.firstname == b.firstname;
}


Though technically to see if they are teh same person wouldn't you want to check if their first name, last name, age, income, number of children, and sex are the same?
Last edited on
Your overloaded operator is not even in scope when you try to use it.
Could you please show me how to do it correctly. I haven't learned this concept in my class yet but I am asked to fix this code in my lab assignment.

I fix it up a little bit. Does this look right ?


#include <iostream>
#include <string>

using namespace std;

struct student_record
{
string firstname, lastname;
double age, income;
int number_of_children;
char sex;
};
Bool operator ==(const student_record &a, const student_record &b);


int main()
{

student_record Mary;
student_record Susan;

cout<<"Enter the firstname and lastname: ";
cin>>Mary.firstname;
cin>>Mary.lastname;
cout<<"Enter age: ";
cin>>Mary.age;
cout<<"Enter income: ";
cin>>Mary.income;
cout<<"Enter number of children: ";
cin>>Mary.number_of_children;
cout<<"Enter sex: ";
cin>>Mary.sex;

Susan = Mary;

if (Susan == Mary)
{
cout<<Susan.firstname<<" "<<Mary.lastname<<endl;
cout<<Susan.age<<endl;
cout<<Susan.income<<endl;
cout<<Susan.number_of_children<<endl;
cout<<Susan.sex<<endl;
}
return 0;
}
bool operator==(const student_record &a, const student_record &b)
{
return a.firstname ==b.firstname;
}
Considering [i]bool[/t] is capitalized when you prototype it, I am going to have to say it doesn't look right. By the way you assign mary to susan so...the if statement should be called every single time.
Thank you. I need to be more careful when I type. I am using a tablet to type right now. That is why I am getting so many typos.
Topic archived. No new replies allowed.