2016-09-14 70 views
0

计算机科学的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”这一行。不会给出错误。另外,我的实验室对这个程序的问题并没有使我看起来好像应该得到一个错误,所以我很困惑。感谢您的任何帮助。

+0

赋值运算符在这种情况下定义,但comparsion运营商从来没有默认定义。 – xinaiz

+0

@BlackMoses如何定义比较运算符? – Bartholomew

+0

比较两个值很容易。比较两个结构/对象是不是。如果它们包含相同的值,两个对象是否相等?或只有他们是同一个对象? –

回答

2

您需要提供comparsion操作:

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 
} 
0

C++提供了一个具有默认构造函数,复制构造函数,赋值运算符(您在此使用)和移动构造函数/赋值的类。

无论好坏,它不会生成运算符==,所以你必须自己做(查找运算符重载)。

检查this question的背后,并进一步参考原因

相关问题