C++类的定义

#include <iostream>
#include <string.h>
#include <time.h>
using namespace std;
class Date;
class Person;
class Date{
private:
    int year,month,day;
public:
    void setDate(int y,int m,int d)
    {
        year = y;
        month = m;
        day = d;
    }
    int getYear(){return year;}
    int getMonth(){return month;}
    int getDay(){return day;}
    bool isLeapYear(){return ((year % 400 == 0) ||(year % 4 == 0 && year %100 !=0));}
    void print(){cout<<year<<"."<<month<<"."<<day<<endl;}
};//日期类

class Person{
private:
    char name[20];
    char sex;//f为女性,m为男性,u为不知性别
    char idno[20];
    Date birthdate;
public:
    void setName(char* s)
    {
        if(strlen(s)<=19)
            strcpy(name,s);
        else
            strcpy(name,"unknown");
    }
    char* getName(){return name;}
    void setSex(char c)
    {
        if(c != 'f' && c!= 'm')
        {
            sex = 'u';
            return;
        }
        sex = 'c';
    }
    char getSex(){return sex;}
    void setIdno(char* id)
    {
        if(strlen(id)>=19)
        {
            strcpy(idno, "unknown");
            return;
        }
        strcpy(idno,id);
    }
    char* getIdno(){return idno;}
    void setBrithdate(int year,int month,int day)
    {
        birthdate.setDate(year,month,day);
    }
    int getAge()
    {
        time_t ltime;//说明time_t结构变量ltime
        time(<ime);//取得当前时间
        tm* today = localtime(<ime);//转换为本地时间
        int ctyear = today->tm_year+1900;//取得当前年份
        return ctyear - birthdate.getYear();
    }
    void show()
    {
        cout<<(sex=='f'?"她是":"他是")<<getName()<<",身份证号为"<<getIdno()<<";";
        cout<<"出生日期为";
        birthdate.print();
        cout<<";年龄为"<<getAge()<<endl;
    }
};

int main()
{
    Person a,b;
    a.setIdno("32011319004094814");
    a.setName("汪涵");
    a.setSex('m');
    a.setBrithdate(1990,4,9);
    a.show();
    b=a;
    b.show();
    b.setIdno("320113198909024815");
    b.setName("丽丽");
    b.setSex('f');
    b.setBrithdate(1989,9,2);
    b.show();

}

猜你喜欢

转载自blog.csdn.net/qq_33614902/article/details/78761213