개발자 '쑥말고인절미'
문제 03-2 [클래스의 정의] 본문
문제 1
- 계산기 기능의 Calculator 클래스를 정의해 보자. 기본적으로 지니는 기능은 덧셈, 뺄셈, 곱셈 그리고 나눗셈이며, 연산을 할 때마다 어떠한 연산을 몇 번 수행했는지 기록되어야 한다. 아래의 main함수와 실행의 예에 부합하는 Calculator 클래스를 정의하면 된다. 단, 멤버변수는 private으로, 멤버함수는 public으로 선언하자.
#include <iostream>
using namespace std;
class Calculator{
    private :
        float a;
        float b;
        int count_Add;
        int count_Min;
        int count_Div;
    public :
        void Init();
        float Add(float input_a, float input_b);
        float Min(float input_a, float input_b);
        float Div(float input_a, float input_b);
        void ShowOpCount();
};
void Calculator::Init(){
    a = 0;
    b = 0;
    count_Add = 0;
    count_Min = 0;
    count_Div = 0;
}
float Calculator::Add(float input_a, float input_b){
    count_Add++;
    return input_a + input_b;
}
float Calculator::Min(float input_a, float input_b){
    count_Min++;
    return input_a - input_b;
}
float Calculator::Div(float input_a, float input_b){
    count_Div++;
    return input_a / input_b;
}
void Calculator::ShowOpCount(){
    cout<<"덧셈 : "<<count_Add<<
          " / 뺄셈 : "<<count_Min<<
          " / 곱셈 : 0"<<
          " / 나눗셈 : "<<count_Div<<endl;
}
int main(void){
    Calculator cal;
    cal.Init();
    cout<<"3.2 + 2.4 = "<<cal.Add(3.2, 2.4)<<endl;
    cout<<"3.5 / 1.7 = "<<cal.Div(3.5, 1.7)<<endl;
    cout<<"2.2 - 1.5 = "<<cal.Min(2.2, 1.5)<<endl;
    cout<<"4.9 / 1.2 = "<<cal.Div(4.9, 1.2)<<endl;
    cal.ShowOpCount();
    return 0;
}
문제2
- 문자열 정보를 내부에 저장하는 Printer라는 이름의 클래스를 디자인하자. 이 클래스의 두 가지 기능은 다음과 같다.
- 문자열 저장
- 문자열 출력
아래의 main 함수와 실행의 예에 부합하는 Printer 클래스를 정의하되, 이번에도 역시 멤버변수는 private으로, 멤버함수는 public으로 선언하자.
#include <iostream>
using namespace std;
class Printer{
    private :
        string str;
    public :
        void SetString(string input_str);
        void ShowString();
};
void Printer::SetString(string input_str){
    str = input_str;
}
void Printer::ShowString(){
    cout<<str<<endl;
}
int main(void){
    Printer pnt;
    pnt.SetString("Hello world!");
    pnt.ShowString();
    
    pnt.SetString("I love C++");
    pnt.ShowString();
    return 0;
}'STUDY > C++ & MFC' 카테고리의 다른 글
| 참조자와 포인터 (0) | 2022.04.06 | 
|---|---|
| 문제 04-2 [다양한 클래스의 정의] (0) | 2022.04.04 | 
| 댓글로 메모 (28) | 2022.04.04 | 
| 문제 04-1 [정보은닉과 const] (0) | 2022.04.04 | 
| 구조체 (0) | 2022.04.04 | 
