9.2> Converter 클래스를 상속받아 km를 mile(마일)로 변환하는 KmToMile 클래스를 작성하라. Main() 함수와 실행 결과는 다음과 같다.
<코드>
#include <iostream> #include <string> using namespace std;
class Converter { protected: double ratio; virtual double convert(double src) = 0; //src를 다른 단위로 변환한다. virtual string getSourceString() = 0; //src 단위 명칭 virtual string getDestString() = 0; //dest 단위 명칭 public: Converter(double ratio) { this->ratio = ratio; } void run() { double src; cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. "; cout << getSourceString() << "을 입력하세요>> "; cin >> src; cout << "변환 결과 : " << convert(src) << getDestString() << endl; //src 받아서 컨버팅 } };
class KmToMile : public Converter{ protected: string from; //바뀌어지는 것의 이름 string to; //바뀐 결과의 이름 public: KmToMile(double ratio, string from, string to); virtual double convert(double src); virtual string getSourceString(); virtual string getDestString(); }; KmToMile::KmToMile(double ratio,string from="Km",string to="Mile"):Converter(ratio){ this->from = from; this->to = to; this->ratio = ratio; //생성자 from,to,ratio 초기화 from과 to의 디폴트는 "Km" "Mile" } double KmToMile::convert(double src){return src/ratio;} string KmToMile::getSourceString() { return from; } //겟소스스트링 함수 오버라이딩 string KmToMile::getDestString() { return to; } //겟dest스트링 함수 오버라이딩
int main(void){ KmToMile toMile(1.609344); //1 mile은 1.609344 Km toMile.run(); return 0; }
|
<결과창>
|
'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글
while, do while loop class (0) | 2017.12.31 |
---|---|
ForLoopAdder 클래스 (0) | 2017.12.31 |
WonToDollar Class (0) | 2017.12.31 |
Printer Class (0) | 2017.12.31 |
ROM RAM class (0) | 2017.12.31 |