实验1 类与对象编程初步
1. 实验目的
(1)掌握类与对象的概念、类成员的概念和类的封装性。
(2)根据给定的要求定义类并实现类的成员函数。
2. 实验内容
(1)日期类、时间类、日期时间类的设计与实现,并设计主程序进行测试。
(2)员工类、员工表类的设计和实现,并设计主程序进行测试。
3. 实验要求
(1)熟悉C++开发环境。
(1)日期类、时间类的属性合理、方法丰富。
(2)使用日期类和时间类,实现日期时间类,并设计日期时间类的相关方法。
(3)员工类的属性合理,方法丰富。
(4)员工表的增加、删除、查找、排序、统计和分析方法的设计,接口简单。
4. 程序代码
(1)时间类设计及测试:
#include<iostream>
using namespace std;
class Time
{
public:
void set_time();
void show_time();
private:
int hour;
int minute;
int sec;
};
int main()
{
Time t1;
t1.set_time();
t1.show_time();
system("pause");
return 0;
}
void Time::set_time()
{
cin >> hour;
cin >> minute;
cin >> sec;
}
void Time::show_time()
{
cout << hour << ":" << minute << ":" << sec << endl;
}
运行结果如图
(2)日期类设计及测试
#include<iostream>
using namespace std;
class Date
{
public:
int year;
int month;
int day;
};
int main()
{
void set_date(Date&);
void show_date(Date&);
Date d1;
set_date(d1);
show_date(d1);
system("pause");
return 0;
}
void set_date(Date& d)
{
cin >> d.year;
cin >> d.month;
cin >> d.day;
}
void show_date(Date& d)
{
cout << d.year << "." << d.month << "." << d.day << endl;
}
运行结果如图
(3)日期时间类实现:
#include<iostream>
#include<string>
using namespace std;
class Date
{
public:
friend class DateTime;
Date(int _year, int _month, int _day) :year(_year), month(_month), day(_day) {}
~Date() {};
void print_date()
{
cout << year << "." << month << "." << day << endl;
}
private:
int year;
int month;
int day;
};
class Time
{
public:
friend class DateTime;
Time(int _hour, int _minute, int _sec) :hour(_hour), minute(_minute), sec(_sec) {}
~Time() {};
void print_time()
{
cout << hour << ":" << minute << ":" << sec << endl;
}
private:
int hour;
int minute;
int sec;
};
class DateTime
{
public:
DateTime() {};
~DateTime() {};
void print(Date& d,Time& t)
{
cout << "输出结果为:" << endl;
d.print_date();
t.print_time();
}
};
int main()
{
Date d(1999, 07, 02);
Time t(12, 41, 25);
DateTime dt;
dt.print(d,t);
system("pause");
return 0;
}
运行结果如图
(4)员工类定义及测试:
#include<iostream>
#include<string>
using namespace std;
class Worker
{
public:
Worker();
virtual void display();
protected:
string name;
string number;
float salary = 0;
};
Worker::Worker()
{
cout << "请输入职工编号:";
cin >> number;
cout << "请输入职工姓名";
cin >> name;
}
void Worker::display()
{
cout << "编号:" << number << "\t" << "姓名:" << name << "\t"<<"工资:"<<salary<<"\n";
cout << endl;
}
int main()
{
Worker a[5];
cout << endl;
int i;
for (i = 0; i < 5; i++)
{
cout << "第" << i + 1 << "个职工信息是:" << endl;
a[i].display();
}
system("pause");
return 0;
}
运行结果如图