目录
题目
(Emloyee类)创建一个名为 Employee(雇员)的类包括作为数据成员的三部分信息:名(类型string)、姓(类型:string)、月薪(类型:int)。[注意:在后续章节中,将使用称为浮点值的包含小数点的数(例如2.75)表示美元数。]这个类还必须包括一个初始化前述的三个数据成员的构造函数。对每个数据成员都提供一个 set 函数和一个get 函数。如果月薪是负数那么设置为0。编写-个演示Employee类性能的测试程序。创建两个Employee 对象,显示每个对象的年薪。然后,对每个Employee对象增薪10%,再显示他们的年薪。
代码
//Employee.h
#include <string>
class Employee
{
public:
Employee(std::string, std::string, int);
void setFirstName(std::string);
void setLastName(std::string);
void setMonthSalary(int);
std::string getFirstName() const;
std::string getLastName() const;
int getMonthSalary() const;
int getYearSalary();
private:
std::string firstName;
std::string lastName;
int monthsalary;
};
//Employee.cpp
#include <iostream>
#include <string>
#include "Employee.h"
using namespace std;
Employee::Employee(string str1, string str2, int num)
{
setFirstName(str1);
setLastName(str2);
setMonthSalary(num);
}
void Employee::setFirstName(string str1)
{
firstName = str1;
}
void Employee::setLastName(string str2)
{
lastName = str2;
}
void Employee::setMonthSalary(int num)
{
monthsalary = num;
}
string Employee::getFirstName() const
{
return firstName;
}
string Employee::getLastName() const
{
return lastName;
}
int Employee::getMonthSalary() const
{
return monthsalary;
}
int Employee::getYearSalary()
{
return monthsalary * 12;
}
主函数
#include <iostream>
#include "Employee.h"
using namespace std;
int main()
{
Employee employee1("wang", "ming", 50);
Employee employee2("zhang", "san", 100);
cout << employee1.getFirstName() << employee1.getLastName()
<< "'s year salary is " << employee1.getYearSalary() << endl;
cout << employee2.getFirstName() << employee2.getLastName()
<< "'s year salary is " << employee2.getYearSalary() << endl;
employee1.setMonthSalary(50 * 1.1);
employee1.setMonthSalary(100 * 1.1);
cout << "增薪10% 后 两人的年薪分别为 :" << endl;
cout << employee1.getFirstName() << employee1.getLastName()
<< "'s year salary is " << employee1.getYearSalary() << endl;
cout << employee2.getFirstName() << employee2.getLastName()
<< "'s year salary is " << employee2.getYearSalary() << endl;
return 0;
}
运行命令
注意:三个文件要放在同一个文件目录下
g++ 3.14main.cpp Employee.cpp -o 3.14main.exe
./3.14main.exe