C++

명품 C++ 3장 2번

NUMERO_K 2018. 10. 28. 14:42

2. 날짜를 다루는 Date 클래스를 작성하고자 한다. Date를 이용하는 main()과 실행 결과는 다음과 같다. 클래스 Date를 작성하여 아래 프로그램에 추가하라.


소스코드


#include <iostream>
#include <string>
using namespace std;
class Date {
public:
    int year, month, day;
    Date(int year, int month, int day);
    Date(string date);
    void show();
    int getYear();
    int getMonth();
    int getDay();
};
Date::Date(int a, int b, int c) { //정수 매개변수를 갖는 생성자
    year = a; month = b; day = c;
}
Date::Date(string a) { // 문자열 매개변수를 갖는 생성자
    year = stoi(a.substr(0, 4));
    month = stoi(a.substr(5, 7));
    day = stoi(a.substr(7, 10));
}
void Date::show() {
    cout << year << "년" << month << "월" << day << "일" << endl;
}
int Date::getYear() {
    return year;
}
int Date::getMonth() {
    return month;
}
int Date::getDay() {
    return day;
}
int main() {
    Date birth(2014, 3, 20);
    Date independenceDay("1945/8/15");
    independenceDay.show();
    cout << birth.getYear() << ',' << birth.getMonth() << ',' << birth.getDay() << endl;
}


실행결과


1번과 다르게 이번에는 생성자도 외부에서 선언하였습니다.

생성자는 리턴 값이 없어야 하므로, 반환 타입도 적지 않습니다.


<string> 헤더 파일의 stoi() 함수를 사용하면 string 문자열을 숫자로 변환할 수 있습니다.

substr(시작위치, 개수)를 사용하면 시작위치부터 개수만큼의 문자열을 반환합니다.



substr 함수에 대한 정보 출처 : http://blog.naver.com/PostView.nhn?blogId=vosej_v&logNo=50176084445&redirect=Dlog&widgetTypeCall=true&directAccess=false