잠토의 잠망경

[C++ STL] 기초 1 - 연산자 오버로딩 본문

공부/Cpp

[C++ STL] 기초 1 - 연산자 오버로딩

잠수함토끼 2014. 7. 29. 21:41

 

아래 코딩을 컴파일 하면 에러가 발생한다.
아래를 고쳐보자.

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
#undef UNICODE
 
#include <iostream>
 
using namespace std;
 
class Point
{
    int x;
    int y;
 
public:
    Point(int _x=0, int _y=0):x(_x), y(_y){}
 
    void Print() const{cout<<x<<','<<y<<endl;}
};
 
 
 
int main(void)
{
    Point p1(2, 3), p2(5,5);
 
    p1 + p2;
    p1 * p2;
    p1 = p2;
    p1 == p2;
    p1 += p2;
 
    return 0;
}

 p1 + p2 를 컴파일 에러를 잡아보자

 

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
#undef UNICODE
 
#include <iostream>
 
using namespace std;
 
class Point
{
    int x;
    int y;
 
public:
    Point(int _x=0, int _y=0):x(_x), y(_y){}
    void Print() const{cout<<x<<','<<y<<endl;}
 
    void operator+(Point arg)
    {
        cout<<"operator+() 함수를 호출"<<endl;
    }
 
 
};
 
 
 
int main(void)
{
    Point p1(2, 3), p2(5,5);
 
    p1 + p2;
//     p1 * p2;
//     p1 = p2;
//     p1 == p2;
//     p1 += p2;
 
    return 0;
}

더 발전을 시켜보자

 

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#undef UNICODE
 
#include <iostream>
 
using namespace std;
 
class Point
{
    int x;
    int y;
 
public:
    Point(int _x=0, int _y=0):x(_x), y(_y){}
 
    int GetX() const                    // const 함수: Class의 멤버변수를 수정하지 않는다.
    {
        return this->x;
    }
 
    int GetY() const                    // const 함수: Class의 멤버변수를 수정하지 않는다.
    {
        return this->y;
    }
 
 
    void SetX(int _x)                    // 비 const 함수
    {
        this->x = _x;
    }
 
    void SetY(int _y)                    // 비 const 함수
    {
        this->y = _y;
    }
    
    void Print() const                    // const 함수: Class의 멤버변수를 수정하지 않는다.
    {
        cout<<x<<','<<y<<endl;
    }
 
    Point operator+(Point arg) const    // const 함수: Class의 멤버변수를 수정하지 않는다.
    {
        cout<<"operator+() 함수를 호출"<<endl;
 
        Point pt;
 
        pt.x = this->x + arg.x;
        pt.y = this->y + arg.y;
 
        return pt;
    }
};
 
 
 
int main(void)
{
    Point p1(2, 3), p2(5,5);
 
    Point p3;
 
 
     p3 = p1 + p2;    // p1.operator+(p2);
 
    p3.Print();
 
    p3 = p1.operator+(p2);
 
    p3.Print();
 
 
//     p1 * p2;    // p1.operator*(p2);
//     p1 = p2;    // p1.operator=(p2);
//     p1 == p2;    // p1.operator==(p2);
//     p1 += p2;    // p1.operator++(p2);
 
    return 0;
}

 

Comments