所以我差不多完成了这个,我无法弄清楚我需要在我的重载输出操作符中返回什么。最初它的返回次数减少了,但我一直得到错误(类型&#34的引用; 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;
}
答案 0 :(得分: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);
}
答案 1 :(得分:0)
根据这里的文件:
http://en.cppreference.com/w/cpp/language/operators
您需要返回参数中的ostream ..
std::ostream& operator<<(std::ostream& os, const Student& obj)
{
return os << obj.stuID << ", " << obj.year << ", " << obj.gpa;
}