一、代理构造、创建不可变对象
#include<iostream>
#include"Date.h"
#include"Employee.h"
//任务4:创建Employ对象,然后修改其生日
/*
注释:创建不可变对象
1.所有数据成员都是私有的
2.没有set函数
3.不返回成员的指针和引用
*/
//下面的例子,返回了指针,也有set函数,所以创建的不是不可变对象
int main()
{
Employee e;
//1.setter
e.setBirthday(Date(1999, 1, 1));
std::cout << e.toString() << std::endl;
//2.getter
e.getBirthday()->setYear(1998);
std::cout << e.toString() << std::endl;
std::cin.get();
return 0;
}
结果如上图所示。
二、相关.h
#pragma once
//任务1:定义Date类
#include<iostream>
#include<string>
class Date
{
private:
int year = 2019, month = 1, day = 1;
public:
int getYear() {
return year; }
int getMonth() {
return month; }
int getDay() {
return day; }
void setYear(int y) {
year = y; }
void setMonth(int m) {
month = m; }
int setDay(int d) {
day = d; }
Date() = default;
Date(int y, int m, int d) :year{
y }, month{
m }, day{
d }{
}
std::string toString()
{
return (std::to_string(year) + "-" + std::to_string(month) + "-" + std::to_string(day));
}//2019-1-1
};
#pragma once
//任务2:定义Gender枚举类型
//任务3:定义Employee类
#include<iostream>
#include<string>
#include"Date.h"
enum class Gender
{
male,
female,
};
class Employee
{
private:
std::string name;
Gender gender;
Date birthday;
public:
void setName(std::string name) {
this->name = name; }
void setGender(Gender gender) {
this->gender = gender; }
void setBirthday(Date birthday) {
this->birthday = birthday; }
std::string getName() {
return name; }
Gender getGender() {
return gender; }
Date* getBirthday() {
return &birthday; }
std::string toString()
{
return (name + (gender == Gender::male ? std::string("male") : std::string("female")) + birthday.toString());
}
Employee(std::string name, Gender gender, Date birthday) :name{
name }, gender{
gender }, birthday{
birthday }{
};
Employee() :Employee("Alan", Gender::male, Date(2000, 4, 1)) {
}
};