-
[C++] Date, Employee.cpp (클래스의 포함 관계)C++/문제풀이 2022. 6. 30. 14:34
Power C++ (p. 488)
문제
날짜를 나타내는 Date 클래스를 정의하라. Date 클래스는 year, month, day를 멤버 변수로 가지며 생성자와 소멸자도 가진다. 이어서 직원을 나타내는 Employee 클래스를 정의한다. Employee 클래스는 직원의 이르과 직원의 생일, 직원의 입사일을 가지고 있다. 생일과 입사일은 Date 객체로 표현된다. Employee 클래스의 생성자는 이름, 생일, 입사일을 매개 변수로 받는다.
#include <iostream> #include <string> using namespace std; // ================ < Date 클래스 > ================ // Step 1. class 생성 class Date { private: int year; int month; int day; public: Date(); Date(int y, int m, int d); ~Date(); int getY(); int getM(); int getD(); void setY(int y); void setM(int m); void setD(int d); void print(); }; //Date 함수 구현부 작성 //디폴트 생성자 Date::Date(){} //매개 변수가 있는 생성자 Date::Date(int y, int m, int d){ year = y; month = m; day = d; } //소멸자 Date::~Date(){} //Date 멤버 함수 외부 정의 int Date::getY(){ return year; } int Date::getM(){ return month; } int Date::getD(){ return day; } void Date::setY(int y){ year = y; } void Date::setM(int m){ month = m; } void Date::setD(int d){ day = d; } void Date::print(){ cout << year << "년 " << month << "월 " << day <<"일"; } // ================ < Employee 클래스 > ================ // Step 1. class 생성 class Employee { private: string name; //이름 Date birth; //생일 Date enterP; //입사일 public: Employee(string n, Date b, Date eP); void print(); }; Employee::Employee(string n, Date b, Date eP){ name = n; birth = b; enterP = eP; } void Employee::print(){ cout << "이름: " << name << endl; cout << "생일: " ; birth.print(); cout << endl; cout << "입사일: " ; enterP.print(); cout << endl; } int main() { // Step 2. 객체 생성 //Date 객체 생성 Date bir(2001, 10, 01); Date hir(2020, 10, 01); //Employee 객체 생성 Employee emp("홍길동", bir, hir); // Step 3. 메세징 emp.print(); return 0; }
[헷갈리는 부분 정리]
1.
class Employee
{
private:
string name; //이름
Date birth; //생일
Date enterP; //입사일
⭐️하나의 객체 안에 다른 객체들이 포함될 수 있다.
⭐️클래스는 다른 클래스의 객체를 멤버로서 가질 수 있다.
2.
void Employee::print(){ cout << "이름: " << name << endl; cout << "생일: " ; birth.print(); cout << endl; cout << "입사일: " ; enterP.print(); cout << endl; }
cout << "생일: " << birth.print() << endl; 은 오류!
출력 스트림은 함수를 출력할 수 없다.
'C++ > 문제풀이' 카테고리의 다른 글
[C++] 클래스 작성 연습.cpp (0) 2022.06.30 [C++] 질문 후 답변이 긍정이면 1, 부정이면 0 반환하는 함수 (0) 2022.06.15 [C++] 문자열이 회문인지 알아보는 프로그램 (0) 2022.06.15 [C++] 문자열 안에 있는 영단어의 개수 계산 (0) 2022.06.15 [C++] 문자열을 입력받아서 문자열에 포함된 모든 공백 문자를 삭제하는 프로그램 (0) 2022.06.15