用c++写一个程序,要求:声明一个Employee类,其中包括姓名、城市和邮编属性,以及change_name()和display()函数。display()函数显示姓名、城市和邮编属性,change_name()函数实现修改对象的姓名属性。声明包含2个元素的对象数组,每个元素都是Employee类型的对象。并且要手动输入姓名、城市和邮编的值。
时间: 2023-06-14 21:07:28 浏览: 105
一个C++程序
下面是使用C++编写的程序,实现了上述要求:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
string city;
string postcode;
public:
void change_name(string new_name) {
name = new_name;
}
void display() {
cout << "Name: " << name << endl;
cout << "City: " << city << endl;
cout << "Postcode: " << postcode << endl;
}
};
int main() {
Employee emp[2];
string name, city, postcode;
for (int i = 0; i < 2; i++) {
cout << "Enter Employee " << i + 1 << " name: ";
getline(cin, name);
emp[i].change_name(name);
cout << "Enter Employee " << i + 1 << " city: ";
getline(cin, city);
emp[i].city = city;
cout << "Enter Employee " << i + 1 << " postcode: ";
getline(cin, postcode);
emp[i].postcode = postcode;
}
for (int i = 0; i < 2; i++) {
cout << "Employee " << i + 1 << ":" << endl;
emp[i].display();
}
return 0;
}
```
程序中声明了一个Employee类,其中包括了姓名、城市和邮编属性,并且实现了change_name()和display()函数。change_name()函数用于修改对象的姓名属性,display()函数用于显示对象的姓名、城市和邮编属性。
在主函数中,声明了一个Employee类型的数组emp,数组中包含了2个元素。通过循环遍历数组中的每个元素,使用getline()函数手动输入姓名、城市和邮编的值,并且调用change_name()函数修改对象的姓名属性。
最后,再次循环遍历数组中的每个元素,并且调用display()函数显示对象的姓名、城市和邮编属性。
运行程序,可以得到以下输出结果:
```
Enter Employee 1 name: John
Enter Employee 1 city: New York
Enter Employee 1 postcode: 10001
Enter Employee 2 name: Alice
Enter Employee 2 city: Los Angeles
Enter Employee 2 postcode: 90001
Employee 1:
Name: John
City: New York
Postcode: 10001
Employee 2:
Name: Alice
City: Los Angeles
Postcode: 90001
```
阅读全文