重载操作符(cin cout 都在这篇文章里出现了 注意区别)

// A code block
#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类练联系在一起了)
friend istream &operator >>(istream& cin,Date &d)//这里一定要引用符号 否则值传到不过去 有的也会在类前加const 不过我不加也执行出来了
{
cin>>d.year>>d.month>>d.day;
//这里可以加上返回 return cin;不过我没加好像也可以执行
}
} ;

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

猜你喜欢

转载自blog.csdn.net/q767410241/article/details/83870376
今日推荐