设为首页 加入收藏

TOP

15.1.5 对象的输入输出
2013-10-07 15:35:29 来源: 作者: 【 】 浏览:87
Tags:15.1.5 对象 输入 输出

15.1.5  对象的输入输出

如果不是基本类型,也可以通过<<运算符输出一个C++(www.cppentry.com)字符串。在C++(www.cppentry.com)中,对象可以描述其输出和输入的方式。这是通过重载<<和>>运算符完成的,重载的运算符可以理解新的类型或类。

为什么要重载这些运算符?如果您已经熟悉了C语言中的printf()函数,那么您应该知道printf()在这方面并不灵活。尽管printf()知道多种数据类型,但是无法让其知道更多的知识。例如,考虑下面这个简单的类:

  1. class Muffin  
  2. {  
  3. public:  
  4. string  getDescription() const;  
  5. void            setDescription(const string& inDesc);  
  6. int                 getSize() const;  
  7. void            setSize(int inSize);  
  8. bool            getHasChocolateChips() const;  
  9. void            setHasChocolateChips(bool inChips);  
  10. protected:  
  11. string  mDesc;  
  12. int                 mSize;  
  13. bool            mHasChocolateChips;  
  14. };  
  15. string Muffin::getDescription() const { return mDesc; }  
  16. void Muffin::setDescription(const string& inDesc) { mDesc = inDesc; }  
  17. int Muffin::getSize() const { return mSize; }  
  18. void Muffin::setSize(int inSize) { mSize = inSize; }  
  19. bool Muffin::getHasChocolateChips() const { return mHasChocolateChips; }  
  20. void Muffin::setHasChocolateChips(bool inChips) { mHasChocolateChips = inChips; }  
  21.  
  22. 代码取自Muffin\Muffi n.cpp  

为了通过printf()输出Muffin类的对象,如果能将其指定为参数,然后再用%m这样的占位符就好了。
  1. printf("Muffin output: %m\n", myMuffin); // BUG! printf doesn't understand Muffin. 

遗憾的是,printf()函数完全不了解Muffin类型,因此无法输出Muffin类型的对象。最糟糕的情况是,由于printf()函数的声明方式,这样的代码会导致运行时错误,而不是一个编译时错误(不过一个好的编译器会给出一个警告消息)。

如果要使用printf(),最多在Muffin类中添加一个新的output()方法。

  1. class Muffin  
  2. {  
  3. public:  
  4. string  getDescription() const;  
  5. void            setDescription(const string& inDesc);  
  6. int                 getSize() const;  
  7. void            setSize(int inSize);  
  8. bool            getHasChocolateChips() const;  
  9. void            setHasChocolateChips(bool inChips);  
  10. void output();  
  11. protected:  
  12. string  mDesc;  
  13. int                 mSize;  
  14. bool            mHasChocolateChips;  
  15. };  
  16. // Other method implementations omitted for brevity  
  17. void Muffin::output()  
  18. {  
  19. printf("%s, Size is %d, %s\n", getDescription().c_str(), getSize(),  
  20. (getHasChocolateChips()   "has chips" : "no chips"));  
  21. }  
  22.  
  23. 代码取自Muffin\Muffin.cpp  

不过,使用这种机制非常笨拙。如果要在另一行文本的中间输出一个Muffin,那么需要将这一行分解为两个调用,在两个调用之间插入一个Muffin::output()调用,如下所示:
  1. printf("The muffin is ");  
  2. myMuffin.output();  
  3. printf(" -- yummy!\n");  

通过重载<<运算符,Muffin的输出就像输出一个string一样简单--只要将其作为<<的参数即可。第18章讲解了运算符<<和>>的重载。
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇15.3.2 将流连接在一起 下一篇15.1.1 流的含义

评论

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

·哈希表 - 菜鸟教程 (2025-12-24 20:18:55)
·MySQL存储引擎InnoDB (2025-12-24 20:18:53)
·索引堆及其优化 - 菜 (2025-12-24 20:18:50)
·Shell 中各种括号的 (2025-12-24 19:50:39)
·Shell 变量 - 菜鸟教 (2025-12-24 19:50:37)