1 流提取和流插入运算符重载
在日期类的输入和输出中,有时我们想通过流提取和流插入运算符,我们还是要通过实现运算符重载解决这个问题。
内置类型是直接支持流插入和流提取的,并且是可以自动识别类型的。这也是因为运算符重载。这是为什么呢?
//流插入 流提取
int i = 1;
double d = 2.2;
cout << i;//自动识别类型
cout << d;
这是因为cout和cin是全局的对象,他们包含在iostream头文件中,所以我们写C++程序要包#include .cin是istream的对象,cout是ostream的对象。因此它俩是两个类型,这个类型是库里面的,流插入和流提取的类型。
我们平时使用时可以直接使用源自于常见的内置类型都重载了。因此cin和cout能够自动识别的原因是因为:函数重载
因此刚刚的代码实际是这样的:
int i = 1;
double d = 2.2;
//函数重载 std::ostream::operator<<
//ostream& operator<<(int val);
cout << i;//自动识别类型
cout.operator<<(i);//实际是这个
cout << d;
但是我们这里是自定义类型怎么办呢?因此我们自己写一个就好了
1.1输出流运算符重载
问题1:
class Date
{
public:
void operator<<(std::ostream& out)
{
out << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
但是此时我们只能通过这种方式来进行访问。
由于成员函数第一个参数是隐含的this无法更改,因此我们写成全局的
写在类外有由于_year,_month,_day是私有的因此我们可以使用友元函数来访问。
class Date
{
//友元函数
//流提取
friend void operator<<(std::ostream& out, const Date& d);
public:
private:
int _year;
int _month;
int _day;
};
//由于成员函数是私有的 我们无法访问
//1.可以使用GetYear() GetMOnth() GetDay()接口 然后在外调用函数
//2.友元函数
void operator<<(std::ostream& out,const Date& d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
}
此时我们发现是可以编译通过的。
问题2:
如果我们想连续访问呢?
此时会先调用cout<<d1,调用完后应该会有一个返回值,这个返回值再去做下一次流插入的左操作数,下一次流插入的左操作数还应该是cout.因此我们这里应该有一个返回值来支持连续流插入。
最终正确版本:
class Date
{
//友元函数
//流提取
friend std::ostream& operator<<(std::ostream& out, const Date& d);
public:
private:
int _year;
int _month;
int _day;
};
//由于成员函数是私有的 我们无法访问
//1.可以使用GetYear() GetMOnth() GetDay()接口 然后在外调用函数
//2.友元函数
std::ostream& operator<<(std::ostream& out,const Date&d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
return out;
}
1.2输入流运算符重载
class Date
{
//友元函数
//流提取
friend std::ostream& operator<<(std::ostream& out, const Date& d);
//流插入
friend std::istream& operator>>(std::istream& in, Date& d);//Date要赋值修改 所以不能const
public:
private:
int _year;
int _month;
int _day;
};
std::ostream& operator<<(std::ostream& out,const Date&d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
return out;
}
std::istream& operator>>(std::istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
return in;
}
int main()
{
Date d1, d2;
cin >> d1;
cout << d1;
cin >> d2;
cout << d2;
return 0;
}