重载操作符(日期类)

#include “iostream”
using namespace std;
class Date
{
private:
int year,month,day;
public:
Date(int a=0,int b=0,int c=0)
{
this->year=a;
this->month=b;
this->day=c;
}
void Show()
{
cout<<year<<"-"<<month<<"-"<<day<<endl;
}
friend ostream &operator <<(ostream& cout,Date d)
{//重载插入符 使得可以直接cout<<自定义的累这种形式的操作可以实现
cout << d.year << “-” << d.month << “-” << d.day;
return cout;
}//ostream &operator<<即为重载操作符做法 在括号中包括的(ostream&cout,Date即把输出和Date类练联系在一起了)
} ;

int main()
{
Date d1(2013,3,20);
cout<<d1<<endl;//直接输出对象d1
d1.Show();//注意与前一句等价
return 0;
}

猜你喜欢

转载自blog.csdn.net/q767410241/article/details/83870101