【转】C++输入输出操作符的重载

操作符的重载有一些规则:

1.  重载操作符必须具有一个类类型或枚举类型操作数。这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含义。

    如: int operator+(int, int), 不可以   

2.  为类设计重载操作符的时候,必须选择是将操作符设置为类成员还是普通非成员函数。在某些情况下,程序没有选择,操作符必须是成员;在另外一些情况下,有些经验可以指导我们做出决定。下面是一些指导:

   a. 赋值(=),下标([]),调用(())和成员访问箭头(->)等操作符必须定义为成员,将这些操作符定义为非成员函数将在编译时标记为错误。

  b. 像赋值一样,复合赋值操作符通常应定义为类的成员。与赋值不同的是,不一定非得这样做,如果定义为非成员复合赋值操作符,不会出现编译错误。

  c. 改变对象状态或与给定类型紧密联系的其他一些操作符,如自增,自减和解引用,通常应定义为类成员。

  d 对称的操作符,如算术操作符,相等操作符,关系操作符和位操作符,最好定义为普通非成员函数。

  e io操作符必须定义为非成员函数,重载为类的友元。

View Code
 1     // OverloadCinCout.cpp : 定义控制台应用程序的入口点。  
 2     //  
 3     #include "stdafx.h"  
 4     #include "iostream"  
 5     #include "string"  
 6       
 7     using namespace std;  
 8       
 9     class Fruit  
10     {  
11     public:  
12         Fruit(const string &nst = "apple", const string &cst = "green"):name(nst),colour(cst){}  
13       
14         ~Fruit(){}  
15       
16         friend ostream& operator << (ostream& os, const Fruit& f);  //输入输出流重载,不是类的成员,  
17       
18         friend istream& operator >> (istream& is, Fruit& f);       // 所以应该声明为类的友元函数  
19       
20     private:  
21         string name;  
22         string colour;  
23     };  
24       
25     ostream& operator << (ostream& os, const Fruit& f)  
26     {  
27         os << "The name is " << f.name << ". The colour is " << f.colour << endl;  
28         return os;  
29     }  
30       
31     istream& operator >> (istream& is, Fruit& f)   
32     {  
33         is >> f.name >> f.colour;  
34         if (!is)  
35         {  
36             cerr << "Wrong input!" << endl;  
37         }  
38         return is;  
39     }  
40       
41     int _tmain(int argc, _TCHAR* argv[])  
42     {  
43         Fruit apple;  
44         cout << "Input the name and colour of a kind of fruit." << endl;  
45         cin >> apple;        
46         cout << apple;  
47         return 0;  
48     }  

 

posted @ 2013-02-23 19:23  xsc906476903  阅读(151)  评论(0编辑  收藏  举报