C++ - 重载I/O操作符的注意(一)

2013-11-20 14:24:42 · 作者: · 浏览: 542

  1. 输出操作符(ostream)重载

  函数: std::ostream &operator《 (std::ostream& os, const ClassA& ca);

  ostream需要修改, 不能复制, 所以应该为非常量引用类型(nonconst &); 输出类不需要修改, 应该为常量引用类型(const &);

  函数有可能使用内部的私有成员, 需要定义为友元(friend);

  重载操作符应该为非类成员函数(nonmember function)。 如果为类成员函数, 则也必须为标准库成员函数, 显然无法完成。

  注意函数不要有格式信息(minimal formatting), 为了和标准输入操作符进行统一。

  2. 输入操作符(istream)重载

  函数: std::istream &operator》 (std::istream& is, ClassA& ca);

  基本同输出操作符;

  参数都为nonconst, 都需要修改;

  操作符函数应该包括错误恢复(error recovery),保证输入错误时, 不会产生未知错误;

  可以增加I/O条件状态(condition state)进行判断, 输入错误原因。

  代码如下, 包含以上所有特性, 注意注释:

  /*

  * cppprimer.cpp

  *

  *  Created on: 2013.11.7

  *

  Author: Caroline

  */

  #include <iostream>

  #include <cstddef>

  #include <utility>

  class HighHeel {

  friend std::ostream &operator《 (std::ostream& os, const HighHeel& hh);

  friend std::istream &operator》 (std::istream& is, HighHeel& hh);

  friend HighHeel operator+ (const HighHeel& lhs, const HighHeel& rhs);

  public:

  int heel() const{

  return (wedgeHeel + kittenHeel + stilettoHeel);

  }

  int boot() const{

  return (kinkyBoot + thighHighBoot);

  }   private:

  int wedgeHeel = 2;

  //坡跟鞋

  int kittenHeel = 2; //中跟鞋

  int stilettoHeel = 2; //细跟鞋

  int kinkyBoot = 5; //长筒女靴

  int thighHighBoot = 5; //过膝长靴

  };

  std::ostream &operator《 (std::ostream& os, const HighHeel& hh)

  {

  os 《 "Heels: " 《 hh.heel() 《 " "

  《 "Boots: " 《 hh.boot();

  return os;

  }