C++的流提取运算符>>和流插入运算符<<能用来输入输出标准类型的数据。这两个运算符是C++编译器在类库中提供的,可以处理包括字符串和内存地址在内的每个标准数据类型。如果我们为自定义类型(C++类)重载这两个运算符,那么他们就也能输入输出该自定义类型。
如下是一个简单的例子,用来处理用户自定义的电话号码类PhoneNumber的数据,源码如下:
类文件:PhoneNumber.h
- #ifndef PHONENUMBER_H
- #define PHONENUMBER_H
- #include <iostream>
- using namespace std;
- //Calling any one of the potentially unsafe methods such as 'readsome' in the Standard C++ Library
- //will result in Compiler Warning (level 1) C4996.
- #pragma warning(disable:4996)
- class PhoneNumber
- {
- public:
- PhoneNumber();
- friend ostream &operator<<(ostream &output, const PhoneNumber &num);
- friend istream &operator>>(istream& input, PhoneNumber &num);
- private:
- char areaCode[4]; //3位数字的区号或为空
- char exchange[4]; //3位数字的电话局号或为空
- char line[5]; //4位数字的线路号或为空
- };
- PhoneNumber::PhoneNumber()
- {
- memset(areaCode, 0, sizeof(areaCode));
- memset(exchange, 0, sizeof(exchange));
- memset(line, 0, sizeof(line));
- }
- ostream &operator<<(ostream& output, const PhoneNumber &num)
- {
- output<<"("<<num.areaCode<<")"<<num.exchange<<"-"<<num.line;
- //使得能连续执行cout<<a<<b<<c;
- return output;
- }
- istream &operator>>(istream& input, PhoneNumber &num)
- {
- input.ignore(); //跳过(
- input.readsome(num.areaCode, sizeof(num.areaCode)-1); //输入区号
- input.ignore(); //跳过)
- input.readsome(num.exchange, sizeof(num.exchange)-1); //输入电话局号
- input.ignore(); //跳过连字符-
- input.readsome(num.line, sizeof(num.line)-1); //输入线路号
- //使得能连续执行cin>>a>>b>>c;
- return input;
- }
- #endif
主程序文件:Main.h
- #include "PhoneNumber.h"
- int main()
- {
- cout<<"--------------------------------------------------------------------/n";
- cout<<" 重载流插入和流提取运算符演示程序 /n";
- cout<<" by Loomman, QQ:28077188, MSN: Loomman@hotmail.com QQ裙:30515563 /n";
- cout<<"--------------------------------------------------------------------/n/n";
- PhoneNumber phone;
- cout<<"Enter a phone number in the form (123)456-789: /n";
- cin>>phone;
- cout<<"The phone number entered was: /n"<<phone<<endl;
- int a;
- cin>>a;
- return a;
- }
运行结果如下:
--------------------------------------------------------------------
重载流插入和流提取运算符演示程序
by Loomman, QQ:28077188, MSN: Loomman@hotmail.com QQ裙:30515563
--------------------------------------------------------------------
Enter a phone number in the form (123)456-789:
(111)222-333
The phone number entered was:
(111)222-333
by Loomman, QQ:28077188, MSN: Loomman@hotmail.com QQ裙:30515563 ☆程序天堂☆ 请尊重作者原创,转载注明来自裂帛一剑博客,谢谢合作。