객체지향프로그래밍2 조교활동 기록

4주차 실습수업 기록 - 멤버변수, 프렌드 함수

su0a 2024. 4. 14. 19:04

퀴즈1. 이 문제는 Employee 클래스 내부에 들어있는 birthDate(생일)와 hireDate(고용년도)를 이용하여 나이를 구해야하는 문제이다.

birthDate, hireDate 모두 Date클래스이므로 Date 클래스의 year 멤버변수를 얻어와 구하면 되는데 학부생들이 private한 멤버변수를 함수를 통해서가 아닌 멤버변수 그대로 얻어와 사용하려고 하여 에러가 발생했었다.

클래스 내에 private을 사용하는 이유, private한 멤버변수는 함수를 통해서 얻는 방법등을 알려주었다.

#pragma once
#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include<string>
#include"Date.h"

class Employee {
public:
	Employee(const std::string&, const std::string&, const Date&, const Date&);
	void print() const;
	int age();
	~Employee();
private:
	std::string firstName;
	std::string lastName;
	const Date birthDate;
	const Date hireDate;
};
#include<iostream>
#include<ctime>
#include"Employee.h"
#include"Date.h"
using namespace std;

Employee::Employee(const string& first, const string& last,
	const Date& dateOfBirth, const Date& dateOfHire)
	:firstName(first), lastName(last), birthDate(dateOfBirth), hireDate(dateOfHire)
{
	cout << "Employee object constructor: "
		<< firstName << ' ' << lastName << endl;

}

void Employee::print() const {
	cout << lastName << ", " << firstName << " Hired: ";
	hireDate.print();
	cout << " Birthday: ";
	birthDate.print();
	cout << endl;
}

int Employee::age() {
	time_t now= time(nullptr);
	int hire_year = hireDate.get_year();
	int birth_year = birthDate.get_year();
	int now_age = hire_year - birth_year + 1;
	return now_age;
}

Employee::~Employee() {
	cout << "Employee object destructor: "
		<< lastName << ", " << firstName << endl;
}
#ifndef DATE_H
#define DATE_H

class Date
{
public:
	static const unsigned int monthsPerYear = 12;
	explicit Date(int = 1, int = 1, int = 1900);
	void print() const;
	int get_year() const;
	~Date();

private:
	unsigned int month;
	unsigned int day;
	unsigned int year;

	unsigned int checkDay(int) const;

};

#endif // DEBUG
#include<array>
#include<iostream>
#include <stdexcept>
#include "Date.h"
using namespace std;

Date::Date(int mn, int dy, int yr) {
	if (mn > 0 && mn <= monthsPerYear)
		month = mn;
	else
		throw invalid_argument("month must be 1-12");
	year = yr;
	day = checkDay(dy);
	cout << "Date object constructor for date ";
	print();
	cout << endl;
}

int Date::get_year() const {
	return year;
}

void Date::print() const {
	cout << month << '/' << day << '/' << year;
}

Date::~Date() {
	cout << "Date object descturctor for date ";
	print();
	cout << endl;
}

unsigned int Date::checkDay(int testDay) const {
	static const array<int, monthsPerYear + 1>daysPerMenth =
	{ 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (testDay > 0 && testDay <= daysPerMenth[month])
		return testDay;
	if (month == 2 && testDay == 29 && (year % 400 == 0 ||
		(year % 4 == 0 && year % 100 != 0)))
		return testDay;
	throw invalid_argument("Invalid day for current month and year");
}

 

 

퀴즈2. 프렌드 함수에 대해 간단한 설명과 사용법을 적어놓았다.