15.1.5 对象的输入输出
如果不是基本类型,也可以通过<<运算符输出一个C++(www.cppentry.com)字符串。在C++(www.cppentry.com)中,对象可以描述其输出和输入的方式。这是通过重载<<和>>运算符完成的,重载的运算符可以理解新的类型或类。
为什么要重载这些运算符?如果您已经熟悉了C语言中的printf()函数,那么您应该知道printf()在这方面并不灵活。尽管printf()知道多种数据类型,但是无法让其知道更多的知识。例如,考虑下面这个简单的类:
- class Muffin
- {
- public:
- string getDescription() const;
- void setDescription(const string& inDesc);
- int getSize() const;
- void setSize(int inSize);
- bool getHasChocolateChips() const;
- void setHasChocolateChips(bool inChips);
- protected:
- string mDesc;
- int mSize;
- bool mHasChocolateChips;
- };
- string Muffin::getDescription() const { return mDesc; }
- void Muffin::setDescription(const string& inDesc) { mDesc = inDesc; }
- int Muffin::getSize() const { return mSize; }
- void Muffin::setSize(int inSize) { mSize = inSize; }
- bool Muffin::getHasChocolateChips() const { return mHasChocolateChips; }
- void Muffin::setHasChocolateChips(bool inChips) { mHasChocolateChips = inChips; }
-
- 代码取自Muffin\Muffi n.cpp
为了通过printf()输出Muffin类的对象,如果能将其指定为参数,然后再用%m这样的占位符就好了。- printf("Muffin output: %m\n", myMuffin); // BUG! printf doesn't understand Muffin.
遗憾的是,printf()函数完全不了解Muffin类型,因此无法输出Muffin类型的对象。最糟糕的情况是,由于printf()函数的声明方式,这样的代码会导致运行时错误,而不是一个编译时错误(不过一个好的编译器会给出一个警告消息)。
如果要使用printf(),最多在Muffin类中添加一个新的output()方法。
- class Muffin
- {
- public:
- string getDescription() const;
- void setDescription(const string& inDesc);
- int getSize() const;
- void setSize(int inSize);
- bool getHasChocolateChips() const;
- void setHasChocolateChips(bool inChips);
- void output();
- protected:
- string mDesc;
- int mSize;
- bool mHasChocolateChips;
- };
- // Other method implementations omitted for brevity
- void Muffin::output()
- {
- printf("%s, Size is %d, %s\n", getDescription().c_str(), getSize(),
- (getHasChocolateChips() "has chips" : "no chips"));
- }
-
- 代码取自Muffin\Muffin.cpp
不过,使用这种机制非常笨拙。如果要在另一行文本的中间输出一个Muffin,那么需要将这一行分解为两个调用,在两个调用之间插入一个Muffin::output()调用,如下所示:- printf("The muffin is ");
- myMuffin.output();
- printf(" -- yummy!\n");
通过重载<<运算符,Muffin的输出就像输出一个string一样简单--只要将其作为<<的参数即可。第18章讲解了运算符<<和>>的重载。