2016-09-14 24 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的背後,並進一步參考原因

相關問題