【发布时间】: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++