【问题标题】:Deciding what to return - bool value决定返回什么 - 布尔值
【发布时间】: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&lt;&lt; 应该直接返回第一个参数。
  • 事实上这就是你所说的要返回,所以返回它(你必须命名它)
  • 您似乎将operator&lt;&lt;operator&lt; 混淆了。
  • if (otherStu.year &lt; otherStu.year) 始终是false

标签: c++ boolean


【解决方案1】:

听起来您对operator&lt;operator&lt;&lt; 感到困惑。

// 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);
}

【讨论】:

    【解决方案2】:

    根据此处的文档:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 2020-03-21
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多