请写出满足以下要求的完整代码,在课后题12.2(创建一个Employee类,该类中有字符数组,表示姓名、街道地址、市、省和邮政编码。把表示构造函数、ChangeName()、Display()的函数原型放在类定义中,构造函数初始化每个成员,Display()函数把完整的对象数据打印出来。其中的数据成员是保护的,函数是公共的。)的基础上: 将姓名构成类Name,其名和姓在该类中为保护数据成员,其构造函数为接收一个指向完整姓名字符串的指针,其Display()函数输出姓名。然后将Employee类中的姓名成员(字符数组)换成Name类对象。 将所有原型化的函数加上成员函数定义,作为类的内部实现文件。 构成完整的类库定义,要求类定义与类的成员函数定义分开。 主函数实现用户信息显示。 int main(){ Employee em("Mark Brooks","5 West St.","Revere","CA","12290"); em.Display(); em.ChangeName("Richard Voss"); em.Display(); }
时间: 2023-05-18 21:02:41 浏览: 72
PostgreSQL12.2 中文资料
以下是满足要求的完整代码:
// Employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <cstring>
class Name {
protected:
std::string firstName;
std::string lastName;
public:
Name(const char* fullName);
void Display() const;
};
class Employee {
protected:
Name name;
std::string streetAddress;
std::string city;
std::string state;
std::string zipCode;
public:
Employee(const char* fullName, const char* street, const char* city, const char* state, const char* zip);
void ChangeName(const char* fullName);
void Display() const;
};
#endif
// Employee.cpp
#include "Employee.h"
Name::Name(const char* fullName) {
std::string nameStr(fullName);
size_t spacePos = nameStr.find(' ');
firstName = nameStr.substr(0, spacePos);
lastName = nameStr.substr(spacePos + 1);
}
void Name::Display() const {
std::cout << firstName << " " << lastName << std::endl;
}
Employee::Employee(const char* fullName, const char* street, const char* city, const char* state, const char* zip)
: name(fullName), streetAddress(street), city(city), state(state), zipCode(zip) {}
void Employee::ChangeName(const char* fullName) {
name = Name(fullName);
}
void Employee::Display() const {
std::cout << "Name: ";
name.Display();
std::cout << "Street Address: " << streetAddress << std::endl;
std::cout << "City: " << city << std::endl;
std::cout << "State: " << state << std::endl;
std::cout << "Zip Code: " << zipCode << std::endl;
}
// main.cpp
#include "Employee.h"
int main() {
Employee em("Mark Brooks", "5 West St.", "Revere", "CA", "12290");
em.Display();
em.ChangeName("Richard Voss");
em.Display();
return 0;
}
阅读全文