C++声明一个Employee类,其中包括姓名、城市和邮编属性,以及change_name()和display()函数。display()函数显示姓名、城市和邮编属性,change_name()函数实现修改对象的姓名属性。声明包含2个元素的对象数组,每个元素都是Employee类型的对象。给对象赋值并输出。
时间: 2023-06-14 13:08:11 浏览: 95
c++ 类的声明和定义
以下是一个实现该功能的C++代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
string name;
string city;
int postal_code;
void change_name(string new_name) {
name = new_name;
}
void display() {
cout << "Name: " << name << endl;
cout << "City: " << city << endl;
cout << "Postal Code: " << postal_code << endl;
}
};
int main() {
Employee employees[2];
employees[0].name = "John";
employees[0].city = "New York";
employees[0].postal_code = 10001;
employees[1].name = "Jane";
employees[1].city = "Los Angeles";
employees[1].postal_code = 90001;
employees[0].display();
cout << endl;
employees[1].display();
cout << endl;
employees[0].change_name("Jack");
employees[0].display();
cout << endl;
employees[1].display();
cout << endl;
return 0;
}
```
输出结果:
```
Name: John
City: New York
Postal Code: 10001
Name: Jane
City: Los Angeles
Postal Code: 90001
Name: Jack
City: New York
Postal Code: 10001
Name: Jane
City: Los Angeles
Postal Code: 90001
```
阅读全文