计算机科学的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”这一行。不会给出错误。另外,我的实验室对这个程序的问题并没有使我看起来好像应该得到一个错误,所以我很困惑。感谢您的任何帮助。
赋值运算符在这种情况下定义,但comparsion运营商从来没有默认定义。 – xinaiz
@BlackMoses如何定义比较运算符? – Bartholomew
比较两个值很容易。比较两个结构/对象是不是。如果它们包含相同的值,两个对象是否相等?或只有他们是同一个对象? –