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

本文介绍了一个使用C++实现的日期类,包括构造函数、显示日期的方法以及重载输入输出运算符来简化日期的读写。通过这个类,可以直接使用cin和cout进行日期的输入和输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值