13.1 Introduction to operator overloading

주홍영·2022년 3월 18일
0

Learncpp.com

목록 보기
144/199

https://www.learncpp.com/cpp-tutorial/introduction-to-operator-overloading/

우리는 lesson 8.9 -- Introduction to function overloading에서 function overloading에 대해서 배운 바 있다. 이는 같은 function name으로 여러 버젼의 function을 호출할 수 있도록 해줬다. 이는 여러 데이터 타입을 하나의 function으로 다룰 수 있도록 해주어 각 function의 detail한 구현마다 이름을 새로 지을 필요가 없도록 해주었다

c++에서 operator는 함수처럼 작동한다. function overloading을 했던 것처럼 operator overloading을 통해 원하는 데이터 타입을 원하는 방법으로 기능을 구현하는 것 또한 가능하다

이번 챕터에서는 function overloading에 대해서 다룬다

Operators as functions

int x { 2 };
int y { 3 };
std::cout << x + y << '\n';

컴파일러에 내장된 operator+에 관한 버전이 존재한다
x + y는 다음과 같이 해석해서 function call을 한다
operator+(x, y) , 이는 operator+가 함수이름인 것과 같다

위와 유사하게 double에서도 가능하다

double z { 2.0 };
double w { 3.0 };
std::cout << w + z << '\n';

이제 user-defined class 타입에서는 어떻게 작동할지 살펴보자

Mystring string1 { "Hello, " };
Mystring string2 { "World!" };
std::cout << string1 + string2 << '\n';

우리는 위의 operator의 동작의 결과로
"Hello, World!"가 print 되기를 기대하고 있다
그러나 Mystring이 user-defined class이므로 컴파일러는 built-in version의
operator+ 의 기능이 존재하지 않는다
따라서 위의 경우에 에러가 발생한다

위의 사례를 의도한 결과를 만들기 위해선 우리는 overloaded function을 만들어 줘야한다

Resolving overloaded operators

operator가 포함된 expression을 평가할 때 compiler는 다음의 룰을 따른다

  • If all of the operands are fundamental data types, the compiler will call a built-in routine if one exists. If one does not exist, the compiler will produce a compiler error.
  • If any of the operands are user data types (e.g. one of your classes, or an enum type), the compiler looks to see whether the type has a matching overloaded operator function that it can call. If it can’t find one, it will try to convert one or more of the user-defined type operands into fundamental data types so it can use a matching built-in operator (via an overloaded typecast, which we’ll cover later in this chapter). If that fails, then it will produce a compile error.

What are the limitations on operator overloading?

first, 대부분의 operator는 overloading이 가능하다
단, conditional (? : ) , sizeof, scope(::), member selector(.). member pointer selector(.*), typeid, and the casting operators를 제외하고 말이다

second, 우리는 오직 존재하는 operator에만 overload를 할 수 있다
새로 operator를 만든다거나 rename하는 것은 불가능하다

third, 적어도 하나의 operand는 user-defined type이어야 한다
즉, 너는 오직 fundamental type으로만 이뤄진 operator overload를 만들 수 없다

Fourth, 우리는 operator가 지원하는 operand의 개수를 바꿀 수 없다

그리고 연산에 대한 우선순위도 존재하기 때문에 혼동이 생길 수 있다
따라서 의도한대로 괄호를 적절하게 사용하는 것이 이때는 도움이 될 것이다

profile
청룡동거주민

0개의 댓글