声明一个 Employee 类,其中包括姓名、地址(使用指针,动态分配空间和设置内容)、邮编等属性,以及 change name、change_address和 display等函数。display()显示姓名、地址、邮编等属性, change_name改变对象的姓名属性,change_address更改地址信息。(可使用cstring函数库中的strcpy、strlen函数) 注意有动态内存分配new操作就要有动态内存释放delete操作。 提示:要有构造函数、拷贝构造函数、析构函数,在构造函数中使用new分配address空间并拷贝内容。然后使用Employee类,设定第一个对象的属性后第二个对象用第一个对象初始化;修改第二个对象的姓名和地址,分别显示每个对象信息;
时间: 2023-06-16 15:07:28 浏览: 56
以下是实现Employee类的代码:
```cpp
#include <iostream>
#include <cstring>
class Employee {
private:
char* name;
char* address;
int postal_code;
public:
Employee(const char* name_, const char* address_, int postal_code_) : postal_code(postal_code_) {
name = new char[strlen(name_) + 1];
strcpy(name, name_);
address = new char[strlen(address_) + 1];
strcpy(address, address_);
}
Employee(const Employee& other) {
name = new char[strlen(other.name) + 1];
strcpy(name, other.name);
address = new char[strlen(other.address) + 1];
strcpy(address, other.address);
postal_code = other.postal_code;
}
~Employee() {
delete[] name;
delete[] address;
}
void change_name(const char* new_name) {
delete[] name;
name = new char[strlen(new_name) + 1];
strcpy(name, new_name);
}
void change_address(const char* new_address) {
delete[] address;
address = new char[strlen(new_address) + 1];
strcpy(address, new_address);
}
void display() const {
std::cout << "Name: " << name << std::endl;
std::cout << "Address: " << address << std::endl;
std::cout << "Postal Code: " << postal_code << std::endl;
}
};
int main() {
Employee e1("John Smith", "123 Main Street", 12345);
Employee e2 = e1;
e2.change_name("Jane Doe");
e2.change_address("456 Elm Street");
std::cout << "Employee 1:" << std::endl;
e1.display();
std::cout << std::endl;
std::cout << "Employee 2:" << std::endl;
e2.display();
return 0;
}
```
输出结果为:
```
Employee 1:
Name: John Smith
Address: 123 Main Street
Postal Code: 12345
Employee 2:
Name: Jane Doe
Address: 456 Elm Street
Postal Code: 12345
```
注意在构造函数中使用new动态分配内存,并在析构函数中使用delete释放内存,以避免内存泄漏。在拷贝构造函数中也要注意进行深拷贝,不能直接复制指针,需要重新分配内存并复制内容。
阅读全文