Skip to main content

重载<<运算符

<<运算符是双目运算符,其左右分别为它的两个参数

一般情况下,<<左边为流的下一个目的地,右边为流入的内容

下例中通过重载<<来输出分数类(Rational)中的内容。(成员a:分子;成员b:分母)

class Rational{
private:
  int a;
  int b;
  //声明友元函数以访问私有成员
  friend std::ostream& operator<<(std::ostream& os , Rational r);

  Rational(int a,int b);     //实现省略
}

std::ostream& operator<<(std::ostream& os , Rational r){
  os<<r.a<<"/"<<r.b;
  return os;
}