Bartholomew
Bartholomew

Reputation: 35

I can't set two user-defined class declared variables equal to each other?

So I am describing output for a foundations of computer science in c++ course, and the directions asked me to copy and paste the following code into my compiler:

#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)// I get the error here: Invalid operands to binary expression('student_record' and 'student_record')
{
    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;
}

I don't quite understand what the problem is as both are of the same type and also the line "Susan = Mary;" doesn't give an error. Also, the questions for this program on my lab does not make it seem as if I was supposed to get an error, so I am confused. Thank You for any help.

Upvotes: 0

Views: 74

Answers (2)

xinaiz
xinaiz

Reputation: 7788

You need to provide comparsion operator:

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

    //operator declaration
    bool operator==(student_record const& other) const;

};

//operator definition
bool student_record::operator==(student_record const& other) const
{
    return (this->firstname == other.firstname &&
            this->lastname == other.lastname &&
            this->sex == other.sex); //you can compare other members if needed
}

Upvotes: 2

Ap31
Ap31

Reputation: 3314

C++ supplies a class with a default constructor, copy constructor, assignment operator (that you use here) and move constructor/assignment.

For better or worse, it does not generate operator==, so you'll have to do it yourself (look up operator overloading).

Check this question for reasons behind this and further reference

Upvotes: 0

Related Questions