2017-04-18 119 views
0

所以我差不多完成了這一點,我不知道我需要返回在我的重載輸出操作符。這本來就是跌的回報少,但我不斷收到錯誤(類型的引用「的std :: ostream的&」(不是常量限定)不能與類型「布爾」的值來初始化)什麼excatly我需要出我return語句?決定什麼返回 - 布爾值

class Student 
{ 
private: 
    int stuID; 
    int year; 
    double gpa; 
public: 
    Student(const int, const int, const double); 
    void showYear(); 
    bool operator<(const Student); 
friend ostream& operator<<(ostream&, const Student&); 
}; 
Student::Student(const int i, int y, const double g) 
{ 
    stuID = i; 
    year = y; 
    gpa = g; 
} 
void Student::showYear() 
{ 
    cout << year; 
} 
ostream& operator<<(ostream&, const Student& otherStu) 
{ 
    bool less = false; 
    if (otherStu.year < otherStu.year) 
    less = true; 
    return ; 
} 
int main() 
{ 
    Student a(111, 2, 3.50), b(222, 1, 3.00); 
    if(a < b) 
    { 
     a.showYear(); 
     cout << " is less than "; 
     b.showYear(); 
    } 
    else 
    { 
    a.showYear(); 
    cout << " is not less than "; 
    b.showYear(); 
    } 
    cout << endl; 
    _getch() 
    return 0; 
} 
+1

按照慣例,'運營商<<'應該直接返回第一個參數。 –

+0

而事實上這是你說什麼你是返回,所以返回它(你得去命名它) – pm100

+2

看來你可能混淆'運營商<<'和'運營商<'。 –

回答

5

這聽起來像你在operator<operator<<之間感到困惑。

// operator< function to compare two objects. 
// Make it a const member function 
bool Student::operator<(const Student& other) const 
{ 
    return (this->year < other.year); 
} 

// operator<< function to output data of one object to a stream. 
// Output the data of a Student 
std::ostream& operator<<(std::ostream& out, const Student& stu) 
{ 
    return (out << stu.stuID << " " << stu.year << " " << stu.gpa); 
}