关于重载流输入输出运算符
尽可能简洁清晰的向同我一样的小白们写范例以便于理解。
以下为单独的流输出重载:
#include<iostream>
#include<string>
using namespace std;
class T
{
public:
friend ostream& operator<<(ostream&, const T&);//声明友元函数,其定义在类定义外
T(double a, double b) :aa(a), bb(b){}//构造函数,并赋初始值
private:
double aa;
double bb;
};
ostream& operator<<(ostream& output, const T& x)//关于流输出运算符的重载函数,其中output和x为自定义命名,可替换
{
output << x.aa / x.bb;
return output;
}
//<<的重载定义为将T类的对象aa/bb
int main()
{
double a = 9;
double b = 3;
T tt(a, b);
cout << tt << endl;//此处因<<重载其定义已变成:tt.aa/tt.bb
}
最后输出的结果为 3
即9/3==3
以下为单独的流输入重载:
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class Date
{
public:
friend istream& operator>>(istream&, Date&);
Date(int a,int b,int c):year(a),month(b),day(c){}
void getDate()
{
cout << year << '.' << month << '.' << day;
}
private:
int year;
int month;
int day;
};
istream& operator>>(istream& input, Date& dd)
{
input >> setw(4) >> dd.year;//将四个宽度内的字符输入至year中
input.ignore(1);//跳过一个宽度内的字符
input >> setw(2) >> dd.month;//将两个宽度内的字符输入至month中
input.ignore(1);
input >> setw(2) >> dd.day;//将两个宽度内的字符输入至day中
return input;
}
int main()
{
Date DD(0,0,0);
cin >> DD;
DD.getDate();
}
我们输入的格式为:2020.09.06
其输出结果为 2020.9.6
如有不当或错误的地方请指出!感谢