我们知道流插入和流提取仅仅对内置类型起作用,那么当我们需要将流插入和流提取对自定义类型起作用时,只能对流插入和流提取重载了
class Date
{
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
//流插入的重载
cout << d1;
return 0;
}
我们无法将cout流插入对d1进行打印
那么我们将 << 进行重载
我们需要将 << 进行重载,需要知道cout对象的类型
cout对象的类型 是ostream
void operator<<(ostream& out) //进行重载
{
out << _year << "-" << _month << "-" << _day << endl;
}
可这样子并不行
原因还是因为隐藏指针this
运算符重载里面,如果是双操作数的操作符重载
第一个操作数传给this指针(左参数),第二个操作数传给(右参数)
那么我们可以返过来---怎么反过来呢
、
这样子是可以解决问题,可是用法太奇怪了(太别扭了) ,不推荐
那么上面分析知道流提取不适合,重载成成员函数 --那么我们把他放在全局里(没有了this指针的影响)
放在全局右面临类的私有成员变量无法在类外访问的问题,那么要将私有成员变量设成公有肯定是不合适的了
那么我们可以引入有元函数:将operator<< 重载函数放在类内,可以访问类内的私有成员变量
class Date
{
//有元函数
friend void operator<<(ostream& out, const Date& d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
}
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
cout << d1;//这样子就可以了
return 0;
}
可是当需要连续输出是却不支持
那么原因是
我们需要将cout进行返回
class Date
{
//有元函数
friend ostream& operator<<(ostream& out, const Date& d)
{
out << d._year << "-" << d._month << "-" << d._day << endl;
return out;
}
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2;
cout << d1 << d2;
//cou<<d1 调用完返回out
//out<<d2 这样子就可以连续输出了
return 0;
}
上面就是对流插入重载函数的讲解,对流提取也是同理的
class Date
{
//有元函数
friend istream& operator>>(istream& in, Date& d)
{
in >> d._year >> d._month >> d._day;
return in;
}
public:
Date(int year = 0, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
void Print() const
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1;
Date d2;
//d1.Print();
//cin >> d1;
//d1.Print();
//d1.Print();
//d2.Print();
//cin >> d1>>d2;
//d1.Print();
//d2.Print();
return 0;
}
以上便是对流插入和流提取重载的讲解