본문 바로가기
카테고리 없음

C++ 실습 동적 할당 계산기 ver1 & ver2

by 리승연 2018. 9. 15.
반응형

동적 할당 계산기 ver1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
 
class Calculator {
 
private:
    int x, y, result;
    char op;
 
public:
    void input() {
        cout << "입력(ex,7+2): ";
        cin >> x >> op >> y;
    }
 
    void cal() {
        switch (op) {
        case'+':result = x + y; break;
        case'-':result = x - y; break;
        case'*':result = x * y; break;
        case'/':result = x / y; break;
        }
    }
 
    void output() {
        cout << result;
    }
};
 
void main() {
    Calculator *= new Calculator;
    n->input();
    n->cal();
    n->output();
 
    delete n;
}

 

동적 할당 계산기 ver2: ver1의 필드를 포인터로

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
using namespace std;
 
class Calculator {
 
private:
    int *x, *y, *result;
    char *op;
 
public:
    Calculator() {
        x = new int;
        y = new int;
        result = new int;
        op = new char;
        
    }
 
    void input() {
        cout << "입력(ex,7+2): ";
        cin >> *>> *op >> *y;
    }
 
    void cal() {
        switch (*op) {
        case'+':*result = *+ *y; break;
        case'-':*result = *- *y; break;
        case'*':*result = ** *y; break;
        case'/':*result = */ *y; break;
        }
    }
 
    void output() {
        cout << *result;
    }
};
 
void main() {
    Calculator *= new Calculator;
    n->input();
    n->cal();
    n->output();
 
    delete n;
}
 

 

 

반응형