【问题标题】:I can't set two user-defined class declared variables equal to each other?我不能将两个用户定义的类声明的变量设置为彼此相等?
【发布时间】:2016-09-14 18:34:57
【问题描述】:

所以我正在描述 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;”这一行没有给出错误。另外,我实验室的这个程序的问题并没有让我看起来好像应该得到一个错误,所以我很困惑。感谢您的帮助。

【问题讨论】:

  • 本例中定义了赋值运算符,但默认情况下从不定义比较运算符。
  • @BlackMoses 如何定义比较运算符?
  • 比较两个值很容易。比较两个结构/对象不是。如果两个对象包含相同的值,它们是否相等?还是仅当它们是相同的对象时?
  • @MarcB 这不是我的代码,这是我教授的代码,所以我不知道她的意思。但我认为她的意思是相同的价值观?

标签: c++


【解决方案1】:

您需要提供比较运算符:

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
}

【讨论】:

    【解决方案2】:

    C++ 为类提供默认构造函数、复制构造函数、赋值运算符(您在此处使用)和移动构造函数/赋值。

    无论好坏,它都不会生成 operator==,因此您必须自己完成(查找运算符重载)。

    查看this question 了解背后的原因并进一步参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多