问题的提出:编写类student,其中包含生日(年、月、日)的私有变量,要求能比较两位学生的年龄差距(精确到多少天),用重载“-”运算符实现年龄差的计算。
/////////ivan.h////////////
#include
#include
#include
#include
using namespace std;
class Age
{
private:
int year;
int month;
int day;
int ytod(const Age&);
bool leap(int);
public:
Age(int year,int month,int day);
int operator -(const Age& s);
Age& operator = ( Age & s);
~Age();
void display();
};
//////////ivan.cc///////////////////
#include"ivan.h"
int mont[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},\
{31,29,31,30,31,30,31,31,30,31,30,31}};
Age::Age(int y=1983,int m=12,int d=8):year(y),month(m),day(d)
{
}
Age::~Age()
{
}
Age& Age::operator=( Age& s)
{
if(this == &s) return s;
year=s.year;
month=s.month;
day=s.day;
return *this;
}
int Age::operator-(const Age& s)
{
return ytod(*this)-ytod(s);
}
void Age::display()
{
cout< }
bool Age::leap(int a)
{
if(a%4 == 0 && a%100 != 0 || a%400 == 0)
return 1;
else return 0;
}
int Age::ytod(const Age& s)
{
int days(0);
for(int i = 1 ; i <= s.year; i++ )
{
if(leap(i))
{
days+=366;
}
else days+=365;
}
if(leap(s.year))
{
for( int m=0 ; m < s.month-1 ; m++ )
{
days+=mont[1][m];
}
}
else
{
for( int m=0 ; m < s.month-1 ; m++ )
{
days += mont[0][m];
}
}
return days+=s.day;
}
////////////////////age.cc////////////
#include"ivan.h"
int main()
{
Age Henry(1980,11,12),Tom(1976,3,25);
cout<<"Henry's birthday is ";Henry.display();
cout<<"Tom's birthday is ";Tom.display();
if((Henry-Tom)>0)
cout<<"Tom is older than Henry "< else
cout<<"Henry is older than Tom "< return 0;
}
//////////////Makefile//////////
CC=g++
age : ivan.o age.o
ivan.o:ivan.h
age.o:ivan.h
$(CC) -c age.cc
.PHONY=clean
clean:
-rm -f *.o age
>make
>./age
Henry's birthday is 1980/11/12
Tom's birthday is 1976/3/25
Tom is older than Henry 1693 days.
阅读(941) | 评论(0) | 转发(0) |