用c++定义一个员工类并举例
时间: 2023-12-30 19:05:03 浏览: 102
cpu.rar_用c++类一个cpu
好的,以下是用 C++ 定义一个员工类的示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
int age;
string address;
double salary;
public:
Employee(string name, int age, string address, double salary) {
this->name = name;
this->age = age;
this->address = address;
this->salary = salary;
}
string getName() {
return name;
}
int getAge() {
return age;
}
string getAddress() {
return address;
}
double getSalary() {
return salary;
}
void setName(string name) {
this->name = name;
}
void setAge(int age) {
this->age = age;
}
void setAddress(string address) {
this->address = address;
}
void setSalary(double salary) {
this->salary = salary;
}
void display() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Address: " << address << endl;
cout << "Salary: " << salary << endl;
}
};
int main() {
Employee employee1("Tom", 25, "Shanghai", 5000.0);
employee1.display();
return 0;
}
```
上述代码定义了一个名为 Employee 的类,包含了员工的姓名、年龄、地址和薪水信息。在类内部,我们定义了一个构造函数用于初始化对象的属性,以及若干个访问器和修改器用于获取和设置对象的属性。最后,我们还定义了一个 display() 函数用于将对象的属性输出到控制台。
在 main() 函数中,我们创建了一个名为 employee1 的 Employee 对象,并调用了它的 display() 函数将其属性输出到控制台。
阅读全文