重载I/O操作符 的 注意

 

本文地址: http://blog.youkuaiyun.com/caroline_wendy/article/details/15336063 

 

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;  }  std::istream &operator>> (std::istream& is, HighHeel& hh)  {  	is >> hh.wedgeHeel >> hh.kittenHeel >> hh.stilettoHeel  		>> hh.kinkyBoot >> hh.thighHighBoot;  	if ( (is.rdstate() & is.failbit) != 0) //检查错误位  		std::cerr << "Error to input!" << std::endl;  	if (!is)  		hh = HighHeel();  	return is;  }    HighHeel operator+ (const HighHeel& lhs, const HighHeel& rhs)  {  	HighHeel sum = lhs;  	sum.wedgeHeel += rhs.wedgeHeel;  	sum.kittenHeel += rhs.kittenHeel;  	sum.stilettoHeel += rhs.stilettoHeel;  	sum.kinkyBoot += rhs.kinkyBoot;  	sum.thighHighBoot += rhs.thighHighBoot;  	return sum;  }    int main (void) {  	HighHeel hh;  	std::cout << hh << std::endl;  	std::cout << "Please input heels quantity (5 numbers) :" << std::endl;  	std::cin >> hh;  	std::cout << hh << std::endl;  	HighHeel hh2;  	std::cout << hh + hh2 << std::endl;  	return 0;  }