-
C++ 연습문제 9.2C++ 2021. 10. 30. 23:42728x90반응형
시간으 나타내는 Time 클래스를 만들어 보자. Time 클래스에는 시(int hour_), 분(int minute_), 초(int second_)를 나타내는 멤버 변수를 포함하고 있다. 다음 main 함수와 실행 결과를 참고하여 두 객체 사이의 + 연산이 가능하도록 만들어 보라.
main.cpp :
#include <iostream> #include "time.h" using namespace std; int main() { Time time1(4, 50, 40); Time time2(3, 40, 30); Time time3 = time1 + time2; time1.Print(); time2.Print(); time3.Print(); return 0; }
내 코드(time.h) :
#include <iostream> using namespace std; class Time { private: int hour_, min_, sec_; public: Time(int hour, int min, int sec) { hour_ = hour; min_ = min; sec_ = sec; } /* Time operator+(const Time& time) { int h = hour_ + time.hour_; int m = min_ + time.min_; int s = sec_ + time.sec_; if (h > 25) h -= 24; if (m >= 60) { h++; m -= 60; } if (s >= 60) { m++; s -= 60; } return Time(h, m, s); */ Time operator+(const Time& time) { if (hour_ + time.hour_ > 25) { if (min_ + time.min_ >= 60) { if (sec_ + time.sec_ >= 60) return Time(hour_ + time.hour_ - 24 + 1, min_ + time.min_ - 60 + 1, sec_ + time.sec_ - 60); else return Time(hour_ + time.hour_ - 24 + 1, min_ + time.min_ - 60, sec_ + time.sec_); } else { if (sec_ + time.sec_ >= 60) return Time(hour_ + time.hour_ - 24, min_ + time.min_ + 1, sec_ + time.sec_ - 60); else return Time(hour_ + time.hour_ - 24, min_ + time.min_, sec_ + time.sec_); } } else { if (min_ + time.min_ >= 60) { if (sec_ + time.sec_ >= 60) return Time(hour_ + time.hour_ + 1, min_ + time.min_ - 60 + 1, sec_ + time.sec_ - 60); else return Time(hour_ + time.hour_ + 1, min_ + time.min_ - 60, sec_ + time.sec_); } else { if (sec_ + time.sec_ >= 60) return Time(hour_ + time.hour_, min_ + time.min_ + 1, sec_ + time.sec_ - 60); else return Time(hour_ + time.hour_, min_ + time.min_, sec_ + time.sec_); } } } void Print() { cout << hour_ << "시 " << min_ << "분 " << sec_ << "초" << endl; } };
다른 변수를 만들면 안될 거 같아서 중첩 if-else문으로 구현하긴 했는데,,, 흠
728x90반응형'C++' 카테고리의 다른 글
C++ 연습문제 9.11 (0) 2021.11.07 C++ 연습문제 9.8 (0) 2021.11.07 C++ 연습문제 8.5 (0) 2021.10.30 C++ 연습문제 7.9 (0) 2021.10.19 C++ 연습문제 7.4 (0) 2021.10.19