C++实验---今年多少岁

今年多少岁

Description
定义类Date,用于表示日期,拥有:

3个int类型属性,分别表示年、月、日。
构造函数、析构函数。要输出一些样例所示的信息。
void show方法,用于输出日期值。格式见样例。
定义类Person,包括
一个Date类的对象用于表示生日,一个字符串表示其姓名(假定不含有空白符)。
构造函数和析构函数。要输出一些样例所示的信息。
int getAge(Date& now)方法,求在当前日期now时的周岁年龄。日期now一定大于birthday。
void show()方法,用于显示Person的信息,格式见样例。
getName()方法,用于返回其名字。
Input
输入3行。第1行包括1个合法的日期的年、月、日三个数据。
第2行是一个不含空白符的字符串,是一个人的名字。
第3行是当前日期,包括年、月、日三个数据。
Output
见样例。
Sample Input

1999 2 2
Tom
2014 5 8

Sample Output

Date 1999-2-2 is created.
Person Tom is created.
Tom’s birthday is 1999-2-2.
Date 2014-5-8 is created.
Now, Tom is 15.
Date 2014-5-8 is erased.
Person Tom is erased.
Date 1999-2-2 is erased.

题目给定代码

int main()
{
    
    
    int y, m, d;
    string name;
    cin >> y >> m >> d >> name;
    Person person(y, m, d, name);
    person.show();
    cin >> y >> m >> d;
    Date now(y, m, d);
    cout << "Now, " << person.getName() << " is " << person.getAge(now) << "." << endl;
    return 0;
}

code:

#include<iostream>
#include<string>
using namespace std;

class Date{
    
    
	int year;
	int month;
	int day;
public:
	Date(int y,int m,int d){
    
    
		year=y;
		month=m;
		day=d;
		cout<<"Date "<<year<<"-"<<month<<"-"<<day<<" is created."<<endl;
	}
	
	~Date(){
    
    
		cout<<"Date "<<year<<"-"<<month<<"-"<<day<<" is erased."<<endl;
	}
	
	void show(){
    
    
		cout<<year<<"-"<<month<<"-"<<day;
	}
	
	int getYear(){
    
    
		return year;
	}
	
};

class Person{
    
    
	Date dd;
	string name;
public:
	Person(int y,int m,int d,string Name):dd(y,m,d){
    
    
		name=Name;
		cout<<"Person "<<name<<" is created."<<endl;
	}
	
	~Person(){
    
    
		cout<<"Person "<<name<<" is erased."<<endl;
	}
	
	int getAge(Date &now){
    
    
		return now.getYear()-dd.getYear();
	}
	
	string getName(){
    
    
		return name;
	}
	
	void show(){
    
    
		cout<<name<<"’s birthday is ";
		dd.show();
		cout<<"."<<endl;
	}
};

int main()
{
    
    
    int y, m, d;
    string name;
    cin >> y >> m >> d >> name;
    Person person(y, m, d, name);
    person.show();
    cin >> y >> m >> d;
    Date now(y, m, d);
    cout << "Now, " << person.getName() << " is " << person.getAge(now) << "." << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/timelessx_x/article/details/115217455