【发布时间】:2017-04-18 18:15:00
【问题描述】:
所以我几乎完成了这个,我无法弄清楚我需要在我的重载输出运算符中返回什么。最初它因返回较少而下降,但我不断收到错误消息(“std::ostream&”类型的引用(非 const 限定)不能用“bool”类型的值初始化)我需要做什么在我的退货声明中?
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;
}
【问题讨论】:
-
按照惯例,
operator<<应该直接返回第一个参数。 -
事实上这就是你所说的要返回,所以返回它(你必须命名它)
-
您似乎将
operator<<与operator<混淆了。 -
if (otherStu.year < otherStu.year)始终是false