1. 流插入和提取运算符
istream& operator>>(istream& input, CTime& time);
istream& operator>>(istream& input, CTime& time);
重载之后就可以直接对 CTime 对象进行输入和输出,程序更加直观
- cout<
1.1 重载后的流插入使用
可以直接使用 cout << time 更加直观化
#include <iostream>
#include "Time.h"
using namespace std;
istream& operator>>(istream& input, CTime& time) {
cin>>time.m_nHour>>time.m_nMinute>>time.m_nSecond;
return input;
}
ostream& operator<<(ostream& input, CTime& time) {
cout<<"Hour:"<<time.m_nHour<<",Minute:"<<time.m_nMinute<<",Second:"<<time.m_nSecond<<endl;
return input;
}
int main() {
CTime time(8,8,8);
// 流插入重载
cin>>time;
cout<<time;
return 0;
}
1.2 头文件定义友元
#ifndef TIME_H
#define TIME_H
#include <iostream>
using namespace std;
class CTime {
public:
CTime(int hour, int minute, int second);
// 流插入
friend istream& operator>>(istream& input, CTime& time);
friend ostream& operator<<(ostream& input, CTime& time);
private:
int m_nHour;
int m_nMinute;
int m_nSecond;
};
#endif