实验2构造函数与对象存储
1. 实验目的
(1)掌握构造函数和析构函数的含义与作用、定义方式和使用方法;
(2)根据要求正确定义和重载构造函数、定义析构函数。
2. 实验内容
(1)日期类、时间类、日期时间类、员工类的构造函数的定义和实现,并在主程序中测试。
(2)员工表类的构造函数和析构函数的定义和实现设计,并在主程序中测试。
3. 实验要求
(1)日期类、时间类、日期时间类、员工类的构造函数有多个实现方式。
(2)员工表类的静态存储方式的实现(静态数组)
(3)员工表类的动态存储方式的实现(动态数组)
4. 程序代码
(1)时间类实现一:
#include<iostream>
using namespace std;
class Time
{
public:
int hour;
int minute;
int sec;
};
int main()
{
Time t1;
cin >> t1.hour;
cin >> t1.minute;
cin >> t1.sec;
cout << t1.hour << ":" << t1.minute << ":" << t1.sec << endl;
system("pause");
return 0;
}
运行结果
(2)时间类实现二:
#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;
}
运行结果:
(3)时间类实现三:
#include<iostream>
using namespace std;
class Time
{
public:
int hour;
int minute;
int sec;
};
int main()
{
void set_time(Time&, int hour = 0, int minute = 0, int sec = 0);
void show_time(Time&);
Time t1;
set_time(t1, 12, 23, 51);
show_time(t1);
system("pause");
return 0;
}
void set_time(Time& t, int hour, int minute, int sec)
{
t.hour = hour;
t.minute = minute;
t.sec = sec;
}
void show_time(Time& t)
{
cout << t.hour << ":" << t.minute << ":" << t.sec << endl;
}
运行结果:
(4)静态员工实现:
#include<iostream>
using namespace std;
class employee
{
public:
employee(int n,int a,float s):name(n),no(a),salary(s){}
void total();
static float average();
private:
int name;
int no;
float salary;
static float sum;
static int count;
};
void employee::total()
{
sum += salary;
count++;
}
float employee::average()
{
return(sum / count);
}
float employee::sum = 0;
int employee::count = 0;
int main()
{
employee empl[3] = {
employee(01,1001,3500),
employee(02,1002,2900),
employee(03,1003,4600)
};
int n;
cout << "输入员工人数:";
cin >> n;
for (int i = 0; i < n; i++)
empl[i].total();
cout << n << "名员工的平均工资为:" << employee::average() << endl;
system("pause");
return 0;
}
运行结果如图: