計算機科學的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
比較兩個值很容易。比較兩個結構/對象是不是。如果它們包含相同的值,兩個對象是否相等?或只有他們是同一個對象? –