-
[overloading] operator <<개발/C·C++ 2021. 7. 28. 14:17
참고
연산자 오버로딩에 적용되는 규칙이 있습니다. 규칙과 관련해서 예제 몇 개를 작성해보겠습니다.
Expression @a as member function
#include <iostream> class Position { private: int x; int y; public: Position() = default; Position(int x, int y) :x(x), y(y) {} Position operator-() const { return Position{ -x, -y }; } void print() const { std::cout << x << ", " << y << std::endl; } }; int main() { Position pos1(2, 3); pos1.print(); Position pos2 = -pos1; // same as pos2 = pos1.operator-() pos2.print(); }
Expression a@b
#include <iostream> class Position { private: int x; int y; public: Position() = default; Position(int x, int y) :x(x), y(y) {} Position operator+(const Position& p) const { return Position{ x + p.x, y + p.y }; } void print() const { std::cout << x << ", " << y << std::endl; } }; int main() { Position pos1{ 2, 3 }; Position pos2{ 3, 3 }; Position pos3 = pos1 + pos2; // same as pos1.operator+(pos2) pos3.print(); }
Expression @a as non-member function
위 예제에서는 멤버 변수 출력을 위해 print()를 정의했습니다. operator<<을 오버로딩 함수를 만들면 멤버 변수을 직관적으로 출력할 수 있습니다. std::cout << pos1 << std::endl; 과 같은 형태가 될 겁니다. 중요한 부분은 std::cout << pos1은 cout.operator<<(pos1)가 아니라는 점입니다. cout이 전역 객체이므로 cout 함수는 전역 함수입니다. 그리고 애초에 수정할 수 없는 라이브러리이기 때문에 cout.operator<<(pos1)의 형태로 호출하는 코드를 작성할 수 없습니다. operator@(a, b)의 형식을 따릅니다. 이 함수에 const를 붙이면 안 되는 이유는, 전역 함수이므로 함수 내부에 this가 없기 때문입니다.
#include <iostream> class Position { private: int x; int y; public: Position() = default; Position(int x, int y) :x(x), y(y) {} friend std::ostream& operator<<(std::ostream& os, Position& p) { return os << p.x << ", " << p.y; } }; int main() { Position pos1{ 2, 3 }; std::cout << pos1 << std::endl; }
'개발 > C·C++' 카테고리의 다른 글
[알고리즘] Quick sort (0) 2021.08.03 [자료구조] doubly linked list (0) 2021.08.02 condition_variable::wait (0) 2021.07.26 Default arguments (0) 2021.07.05 [Template] 템플릿 구체화 (0) 2021.07.05