
这道C++编程题怎么做?如何利用友元计算两个日期相差的天数?求大神解答
2个回答
展开全部
#include<iostream>
using namespace std;
class MyDate{
private:
int year;
int month;
int day;
public:
MyDate(int _y,int _m,int _d);
void showDate();
friend int TD(MyDate &a,MyDate &b);//友元函数是朋友,不是家庭(类)成员。
MyDate::MyDate(int _y,int _m,int _d)
{
year=_y;
month=_m;
day=_d;
}
void MyDate::showDate(){
cout<<"日期是:"<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
}
int TD(MyDate &a,MyDate &b){
int days= (b.year-a.year)*365+(b.month-a.month)*30+(b.day-a.day);
if (days<0) return -days;
else return days;
}
int main()
{
MyDate a(2005,10,12);
MyDate b(2006,12,26);
a.showDate();
b.showDate();
cout<<"两者差:"<<TD(a,b)<<"天";
return 0;
}
我好蛋疼。本来在学js,现在搁着撸C++。算了,当复习啦哈哈。
追问
谢谢啦~虽然有一点小错误
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询