我不能将两个用户定义的类声明变量设置为彼此相等?

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

本文关键字:设置 变量 声明 不能 定义 用户 两个      更新时间:2023-10-16

所以我正在描述c++课程中计算机科学基础的输出,并且指示要求我复制并粘贴以下代码到我的编译器中:

#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;
}

我不太明白问题出在哪里,因为两者是同一类型的,而且"Susan = Mary;"这一行也没有给出错误。此外,这个程序的问题在我的实验室没有使它看起来好像我应该得到一个错误,所以我很困惑。谢谢你的帮助。

您需要提供比较操作符:

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
}

c++为类提供了默认构造函数、复制构造函数、赋值操作符(此处使用)和移动构造函数/赋值操作。

不管怎样,它不会生成operator==,所以你必须自己做(查找operator重载)。

检查这个问题背后的原因,并进一步参考