关于<<重载问题
程序代码:
#include <cmath> #include <iostream> using namespace std; class Date { private: int year; int month; int day; public: Date(int a=0,int b=0,int c=0);// ~Date(){} //int monthdays(int a,int b); //Date operator +(const Date &t)const; Date operator +(const int a)const; int operator -(const Date &t)const; Date operator -(const int a)const; void operator<<(ostream & os); }; Date::Date(int a,int b,int c) { year=a; month=b; day=c; } int monthdays(int a,int b) { if(b==1||b==3||b==5||b==7||b==8||b==10||b==12) return 31; else if(b==2) { if(a%4==0&&a%100!=0||a%400==0) return 29; else return 28; } else return 30; } //似乎用不到日期加日期 /*Date Date::operator+(const Date &t)const { Date sum; Date count(t.year,t.month); for(int i=0;i<(year-t.year)*12+month-t.month;i++) { sum.day=(day+t.day)%monthdays(count.year,count.month); sum.month=(month+t.month+(day+t.day)/monthdays(count.year,count.month))%12; sum.year=(year+t.year+(month+t.month+(day+t.day)/monthdays(count.year,count.month)))/12; count.year++; count.month++; } return sum; }*/ Date Date::operator+(const int a)const { Date sum; Date count(year,month); int b=a,i=0; while (b>monthdays(count.year,count.month)) { i++; b-=monthdays(count.year,count.month); count.month; if(count.month>12) { count.month%=12; count.year++; } } sum.day=day+b; sum.month=month+i+sum.day/monthdays(count.year,count.month); sum.year=year+month/12; sum.month%=12; sum.day%=monthdays(count.year,count.month); return sum; } int Date::operator-(const Date &t)const { Date count(t.year,t.month); int sum=0; while (year!=count.year||month!=count.month) { sum+=monthdays(count.year,count.month); count.month++; if(count.month>12) { count.month%=12; count.year++; } } sum+=day-t.day; return sum; } Date Date::operator-(const int a)const { Date count(year,month); Date sum; int b=a; while(b>monthdays(count.year,count.month)) { } return sum; } void Date::operator<<(ostream & os) { os<<year<<'-'<<month<<'-'<<day<<endl; } //#include <iostream> //using namespace std; //#include "Date.h" int main() { Date t1(2012,1,1); int a=366; cout<<t1+a<<endl; system("pause"); return 0; }如果想要想在主函数里这样输出成员对象,该怎么重载<<啊?谢谢了。