en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading#Arithmetic_operators
 

C++ Programming/Operators/Operator Overloading - Wikibooks, open books for an open world

From Wikibooks, open books for an open world Jump to navigation Jump to search Operator overloading[edit] Operator overloading (less commonly known as ad-hoc polymorphism) is a specific case of polymorphism (part of the OO nature of the language) in which

en.wikibooks.org

각종 연산자 오버로딩한 코드를 snippet처럼 모아두기 위한 글.


Arithmetic (+, -, *, /, ...)
pii operator+(const pii& p1, const pii& p2){
	return {p1.first+p2.first, p1.second+p2.second};
}

 

Class/Struct에 대한 연산자를 내부에서 overloading하는 경우, rhs에 해당하는 parameter 1개만 필요

class SampleObj{
  ...
  
  SampleObj operator+(const SampleObj& rhs){
      return ...;
  }	
}

https://www.geeksforgeeks.org/operator-overloading-c/

 

 

Compound assignment operator (+=, -=, ...)

 

pair<int, int> 에 += operator overloading 해보려고 했는데 안되는 것 같더라.

// Expected : pii a {1,2}, b {-1,-1}; a+=b; // a {0,1}, b {-1, -1}
// Cannot be overloaded
pii& operator+=(pii& p1, pii& p2) { 
	...
}

 

맨 위 링크 Wiki 찾아보니, compound assignment operator는 클래스의 member 함수로만 오버로딩 할 수 있다네.

Compound assignment operators should be overloaded as member functions, as they change the left-hand operand.

Built-in class인 pair의 멤버 함수 정의를 추가/변경 할 수 없으니, 아마 안되는 것으로 받아들여도 될 듯.

 

* '멤버 함수 기반으로만 오버로딩 되는 연산자' (ex. [], ->, = 대입, () 함수 호출) 관련 포스트

맨 위 위키에서 보면 'must be a member function' 라는 말이 붙어있다.

링크

 

 

Assignment operator (=)

(링크) [ C++ ] 대입 연산자 오버로딩

→ Move semantics를 통해 최적화 가능 (공부!)

 

 

Input/Output 오버로딩
// 예시) 벡터 출력
template<typename Os, typename V>
Os& operator<< (Os& os, V const& v) {
    os << "{ ";
    for (auto const& e : v) os << e << ' ';
    return os << "}";
}

 

 

Comparison operator 오버로딩 (<, >, <=, >=)
bool operator< (const pii& p1, const pii& p2) {
    if (p1.first < p2.first)
        return true;
    else
        return p1.second < p2.second;
}

 

 


[참고] 사용자 정의 클래스에 대한 연산자 오버로딩

edykim.com/ko/post/c-operator-overloading-guidelines/

 

C++ 연산자 오버로딩 가이드라인

이 가이드라인은 California Institute of Technology의 강의 자료인 C++ Operator Overloading Guidelines를 번역한 글로 C++에서 연산자를 오버로딩 할 때 유의해야 하는 부분을 잘 설명하고 있다. …

edykim.com

C++ 연산자 오버로딩 가이드라인 _ 매일 성장하기.mhtml
0.22MB

+ Recent posts