C++ 12일차
연산자 오버로딩
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 | #include <iostream> #include <cstdio> using namespace std; class Vector2 { public: Vector2(); Vector2(float x, float y); float GetX() const; float GetY() const; Vector2 operator+(const Vector2 rhs) const; private: float x; float y; }; Vector2 Sum(Vector2 a, Vector2 b) { return Vector2(a.GetX() + b.GetX(), b.GetX() + b.GetY()); } int main(void) { Vector2 a(2, 3); Vector2 b(-1, 4); Vector2 c1 = a.operator+(b); Vector2 c2 = a + b; cout << a.GetX() << " " << a.GetY() << endl; cout << b.GetX() << " " << b.GetY() << endl; cout << c1.GetX() << " " << c1.GetY() << endl; cout << c2.GetX() << " " << c2.GetY() << endl; getchar(); return 0; } Vector2::Vector2() : x(0), y(0) {} Vector2::Vector2(float x, float y) : x(x), y(y) {} float Vector2::GetX() const { return x; } float Vector2::GetY() const { return y; } Vector2 Vector2::operator+(const Vector2 rhs) const { return Vector2(x + rhs.x, y + rhs.y); } | cs |
위의 예제는 a라는 객체를 만들고 그다음 b라는 객체를 만든다. 그리고 operator라는 것을 이용하여 객체를 연산하게 하게 되는 데 이것을 연산자 오버로딩이라고 한다. 먼저위의 예제를 입력하여 출력하게 될경우
2 3
-1 4
1 7
1 7
이런식으로 나타나게 된다. 위의 28번을 보면 객체를 연산하는데 이것이 가능하다. 원래라면 구문오류가 있어야 되겠지만 operator라는 함수가 있기에 저것이 가능하다. 이것을 연산자 오버로딩이다. 연산자 오버로딩을 다른 사칙연산으로 바꾸는 것도 가능하다.