输出一个学生的学号,姓名,性别和出生年月日
class Date
{
public:
Date(int y, int m, int d) :m_year(y), m_month(m), m_day(d) {}
void Print()
{
cout << m_year << "/" << m_month << "/" << m_day << endl;
}
private:
int m_year;
int m_month;
int m_day;
};
class student
{
public:
student(int num, const char* name, char sex, int y, int m, int d) :m_num(num), m_sex(sex), birthday(y, m, d)
//因为m_name是指针类型的数据成员,所以不可以在成员初始化列表中直接初始化。
//因为birthday是Date类的对象,Date类构造函数是有参数的构造函数,需要进行传参,所以m_year、m_month、m_day在student的初始化需要直接调用birthday将y,m,d给它传过去
{
m_name = new char[strlen(name) + 1];
strcpy_s(m_name, strlen(name) + 1, name);
}
~student()
{
if (m_name != NULL)
{
delete[]m_name;
m_name = NULL;
}
}
void Show()
{
cout << m_num << " " << m_name << " " << m_sex << " ";
birthday.Print();//调用接口去输出年月日的值
}
private:
int m_num;
char* m_name;
char m_sex;
Date birthday;
};
void main()
{
student s1(1001, "lisi", 'm', 2000, 12, 12);
s1.Show();
}
运行结果: