ConsoleApplication1.h 头文件定义类 Student myDate
#include <vector>
using namespace std;
#pragma once
int main();
class myDate
{
public:
myDate(); //构造函数
myDate(int, int, int);//构造函数
void setDate(int, int, int);//设置日期
void setDate(myDate);//设置日期
myDate getDate();//设置日期
void setYear(int);//设置年
int getMonth();//获取月
void printDate()const;//打印日期
private:
int year, month, day;//成员变量,表示 年 月 日
};
class Student {
public:
void setStudent(string, myDate);
void setName(string);
string getName();
void setBirthday(myDate);
myDate getBirthday();
void printStudent()const;
private:
string name;
myDate birthday;
};
Student 类
#include <iostream>
using namespace std;
#include <string>
#include "ConsoleApplication1.h"
void Student::setStudent(string s, myDate d)
{
name = s;
birthday.setDate(d);
return;
}
void Student::setName(string n)
{
name = n;
return;
}
string Student::getName()
{
return name;
}
void Student::setBirthday(myDate d)
{
birthday.setDate(d);
return;
}
myDate Student::getBirthday()
{
return birthday;
}
void Student::printStudent()const
{
cout << "姓名:" << name << "\t生日:";
birthday.printDate();
cout << endl;
}
myDate 类
#include <iostream>
using namespace std;
#include "ConsoleApplication1.h"
//在类体外定义成员函数
myDate::myDate() {
year = 1970, month = 1, day = 1;
}
myDate::myDate(int y, int m, int d) {
year = y; month = m; day = d;
}
void myDate::setDate(int y, int m, int d)
{
year = y; month = m; day = d;
return;
}
void myDate::setDate(myDate oneD)
{
year = oneD.year; month = oneD.month; day = oneD.day;
return;
}
myDate myDate::getDate()
{
return *this;
}
void myDate::setYear(int y)
{
year = y;
return;
}
int myDate::getMonth() {
return month;
}
void myDate::printDate()const
{
cout << year << "/" << month << "/" << day;
return;
}
第二章课本测试3验证类功能的驱动程序.cpp
#include <iostream>
using namespace std;
#include <string>
#include "ConsoleApplication1.h"
int main()
{
Student ss;
int y, m, d;
string name_;
cout << "请输入学生的姓名和生气,生日以/年月日/的次序输入";
cin >>name_ >> y >> m >> d;
ss.setStudent(name_, myDate(y, m, d));
ss.printStudent();
return 0;
}
第二章课本测试4使用指针的方式驱动程序.cpp
#include <iostream>
using namespace std;
#include "ConsoleApplication1.h"
#include <string>
int main()
{
Student ss;
int y, m, d;
string name_;
Student *sp = &ss; //指向ss的指针sp
cout << "请输入学生的姓名和生日,生日以/年 月 日 /的次序输入";
cin >> name_ >> y >> m >> d;
sp->setStudent(name_, myDate(y, m, d));
sp->printStudent();
return 0;
}
第二章课本测试5使用引用访问对象的成员.cpp
#include <iostream>
#include <string>
using namespace std;
#include "ConsoleApplication1.h"
int main()
{
Student ss;
int y, m, d;
string name_;
Student &sy = ss;
cout << "请输入学生的姓名和生日,生日 以 年 月 日 的次序输入";
cin >> name_ >> y >> m >> d;
sy.setStudent(name_, myDate(y, m, d));
sy.printStudent();
return 0;
}