C ++実験---今年は何歳ですか

これは何歳ですか

説明
は、日付を表すために使用されるクラスDateを定義し、次のものがあります。

3つのint型属性は、それぞれ年、月、日を表します。
コンストラクタ、デストラクタ。サンプルに示されている情報を出力します。
void showメソッドは、日付値を出力するために使用されます。形式については、例を参照してください。誕生日を表すために使用されるDateクラスのオブジェクトと、その名前を表す文字列を
含む、クラスPersonを定義し
ます(空白が含まれていないことを前提とします)。
コンストラクタとデストラクタ。サンプルに示されている情報を出力します。
int getAge(Date&now)メソッドは、現在の日付の年齢を検索します。日付は誕生日より大きくなければなりません。
void show()メソッドは、Personの情報を表示するために使用されます。形式については、例を参照してください。
getName()メソッドは、その名前を返すために使用されます。3行
入力し
ます。最初の行には、法定日付の年、月、日の3つのデータが含まれています。
2行目は、人の名前である空白のない文字列です。
3行目は現在の日付で、年、月、日の3つのデータが含まれています。
出力
の例を参照してください。
サンプル入力

1999 2 2
Tom
2014 5 8

サンプル出力

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;
}

コード:

#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