프로그래밍/C, C++

c++ 연산자 오버로딩

즉흥 2014. 10. 29. 09:11
728x90
반응형

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<iostream>
using namespace std;
class test{
public:
    int a, b;
    test(int a, int b)
        :a(a), b(b)
    {}
    void show(){
        cout << a << ' ' << b << endl;
    }
    test operator+(const  test &t){
        test ret(a + t.a, b + t.b);
        return ret;
    }
};
int main(){
    test a(1, 2), b(3, 4);
    test c = a + b;
    c.show();
    return 0;
}
a.operator+(b) 혹은 b.operator+(a)라고 써도 a+b와 결과가 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;
class test{
public:
    int a, b;
    test(int a, int b)
        :a(a), b(b)
    {}
    void show(){
        cout << a << ' ' << b << endl;
    }
    friend test operator+(const  test &t1, const test &t2);
};
test operator+(const test &t1, const test &t2){
    test ret(t1.a + t2.a, t1.b + t2.b);
    return ret;
}
int main(){
    test a(1, 2), b(3, 4);
    test c = a + b;
    c.show();
    return 0;
}

operator+(a,b)라고 써도 a+b와 결과가 같다.


두 코드의 결과는 위와 같다.



첫 번째 코드가 멤버 함수를 사용한 연산자 오버로딩이고 두 번째 코드가 전역 함수를 사용한 연산자 오버로딩이다.


우선순위는 전자가 후자보다 높다.

728x90
반응형