编写能创建具有生日(Date)的Person类,可通过构造函数(包括拷贝构造函数)初始化生日,显示打印人的生日,并设置static成员变量来记录Person类有多少个对象,通过static成员函数返回该变量值
date和person类要有无参构造函数和带参构造函数等
#include <iostream>
#include <iomanip>
using namespace std;
class Date
{
public:
int year;
int month;
int day;
Date() : year(0), month(0), day(0) {}
Date(int y, int m, int d) : year(y), month(m), day(d) {}
Date(const Date &d)
{
year = d.year;
month = d.month;
day = d.day;
}
Date &operator=(const Date &d)
{
year = d.year;
month = d.month;
day = d.day;
}
friend ostream &operator<<(ostream &os, const Date &d)
{
cout.fill('0');
os << setw(4) << d.year << ":" << setw(2) << d.month << ":" << setw(2) << d.day << endl;
}
};
class Person
{
static int s_count;
public:
Date birth;
Person()
{
birth = Date();
s_count++;
}
Person(int y, int m, int d)
{
birth = Date(y, m, d);
s_count++;
}
Person(const Person &p)
{
birth = p.birth;
s_count++;
}
~Person() { s_count--; }
static int Count() { return s_count; }
};
int Person::s_count = 0;
int main()
{
Person a; //无参构造
cout << "Birth: " << a.birth;
cout << "Person: " << Person::Count() << endl;
Person b(2077, 2, 3); //带参构造
cout << "Birth: " << b.birth;
cout << "Person: " << Person::Count() << endl;
{
Person c(b); //拷贝构造
cout << "Birth: " << c.birth;
cout << "Person: " << Person::Count() << endl;
}
cout << "After ~Person():" << Person::Count() << endl;
return 0;
}
// 输出:
// Birth: 0000:00:00
// Person: 1
// Birth: 2077:02:03
// Person: 2
// Birth: 2077:02:03
// Person: 3
// After ~Person():2