C++输入输出操作符的重载
操作符的重载有一些规则:
1. 重载操作符必须具有一个类类型或枚举类型操作数。这条规则强制重载操作符不能重新定义用于内置类型对象的操作符的含义。
如: int operator+(int, int), 不可以
2. 为类设计重载操作符的时候,必须选择是将操作符设置为类成员还是普通非成员函数。在某些情况下,程序没有选择,操作符必须是成员;在另外一些情况下,有些经验可以指导我们做出决定。下面是一些指导:
a. 赋值(=),下标([]),调用(())和成员访问箭头(->)等操作符必须定义为成员,将这些操作符定义为非成员函数将在编译时标记为错误。
b. 像赋值一样,复合赋值操作符通常应定义为类的成员。与赋值不同的是,不一定非得这样做,如果定义为非成员复合赋值操作符,不会出现编译错误。
c. 改变对象状态或与给定类型紧密联系的其他一些操作符,如自增,自减和解引用,通常应定义为类成员。
d 对称的操作符,如算术操作符,相等操作符,关系操作符和位操作符,最好定义为普通非成员函数。
e io操作符必须定义为非成员函数,重载为类的友元。
- // OverloadCinCout.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include "iostream"
- #include "string"
- using namespace std;
- class Fruit
- {
- public:
- Fruit(const string &nst = "apple", const string &cst = "green"):name(nst),colour(cst){}
- ~Fruit(){}
- friend ostream& operator << (ostream& os, const Fruit& f); //输入输出流重载,不是类的成员,
- friend istream& operator >> (istream& is, Fruit& f); // 所以应该声明为类的友元函数
- private:
- string name;
- string colour;
- };
- ostream& operator << (ostream& os, const Fruit& f)
- {
- os << "The name is " << f.name << ". The colour is " << f.colour << endl;
- return os;
- }
- istream& operator >> (istream& is, Fruit& f)
- {
- is >> f.name >> f.colour;
- if (!is)
- {
- cerr << "Wrong input!" << endl;
- }
- return is;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- Fruit apple;
- cout << "Input the name and colour of a kind of fruit." << endl;
- cin >> apple;
- cout << apple;
- return 0;
- }