设为首页 加入收藏

TOP

C++ - 重载I/O操作符的注意(一)
2013-11-20 14:24:42 来源: 作者: 【 】 浏览:528
Tags:  重载 I/O 操作 符的 注意

  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;

  }

   

首页 上一页 1 2 3 4 5 下一页 尾页 1/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇c++中*& 和**& 符合作.. 下一篇C++指向函数的指针

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·PostgreSQL 索引 - (2025-12-25 22:20:43)
·MySQL Node.js 连接 (2025-12-25 22:20:41)
·SQL 撤销索引、表以 (2025-12-25 22:20:38)
·Linux系统简介 (2025-12-25 21:55:25)
·Linux安装MySQL过程 (2025-12-25 21:55:22)