用C++写代码:创建一个 Employee 类,该类中有字符数组,表示姓名、街道地址、市、省和邮政编码。把表示构造函数、ChangeName()、Display()的函数原型放在类定义中,构造函数初始化每个成员,Display()函数把完整的对象数据打印出来。其中的数据成员是保护的,函数是公共的。将姓名构成类 Name,其名和姓在该类中为保护数据成员,其构造函数为接收一个指向完整姓名字符串的指针,其 Display()函数输出姓名。然后将Employee 类中的姓名成员(字符数组)换成 Name 类对象。将所有原型化的函数加上成员函数定义,作为类的内部实现文件构成完整的类库定义,要求类定义与类的成员函数定义分开。
时间: 2023-06-20 09:10:38 浏览: 127
以下是完整的类库定义:
Employee.h
```cpp
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include "Name.h"
class Employee {
protected:
Name name;
char address[100];
char city[50];
char state[50];
char zip[20];
public:
Employee(const char* fullName, const char* address, const char* city, const char* state, const char* zip);
void ChangeName(const char* fullName);
void Display() const;
};
#endif
```
Employee.cpp
```cpp
#include "Employee.h"
#include <iostream>
Employee::Employee(const char* fullName, const char* address, const char* city, const char* state, const char* zip)
: name(fullName) {
strcpy_s(this->address, address);
strcpy_s(this->city, city);
strcpy_s(this->state, state);
strcpy_s(this->zip, zip);
}
void Employee::ChangeName(const char* fullName) {
name = Name(fullName);
}
void Employee::Display() const {
std::cout << "Name: ";
name.Display();
std::cout << "Address: " << address << std::endl;
std::cout << "City: " << city << std::endl;
std::cout << "State: " << state << std::endl;
std::cout << "Zip: " << zip << std::endl;
}
```
Name.h
```cpp
#ifndef NAME_H
#define NAME_H
class Name {
protected:
char firstName[50];
char lastName[50];
public:
Name(const char* fullName);
void Display() const;
};
#endif
```
Name.cpp
```cpp
#include "Name.h"
#include <iostream>
Name::Name(const char* fullName) {
// Split full name into first and last names
int spaceIndex = strchr(fullName, ' ') - fullName;
strncpy_s(firstName, fullName, spaceIndex);
firstName[spaceIndex] = '\0';
strcpy_s(lastName, fullName + spaceIndex + 1);
}
void Name::Display() const {
std::cout << firstName << " " << lastName << std::endl;
}
```
阅读全文