Qaupot Blog
Software Engineering, Trip

305. 2항 연산자 오버로딩

🕐 Mon, 24 Feb 2014 09:00:00 GMT 🕓 Tue, 31 Aug 2021 13:03:00 GMT

2항(이항,Binary) 연산자 오버로딩

2항 연산자는 클래스 멤버로 선언할 때는 자기 자신과 별도의 1개의 인수를 이용합니다. 전역에 선언할 경우에는 인수를 2개 지정합니다.

2항 연산자는 문법상 연산자 자신을 기준으로 좌우로 인수가 지정합니다.

  • A + B의 표현식이라면 +연산자의 인수는 A와 B가 되는 것과 같습니다.
  • 흔히, 좌측의 인수를 lhs(left hand side) 우측의 인수를 rhs(right hand side)라고 부릅니다.

일반적인 연산자와 마찬가지로 연산자 우선순위가 높은 연산자부터 호출됩니다.

사칙연산

Operator Description
% Modulus
Subtraction
%= Modulus with assignment
–= Subtraction with assignment
* Multiplication
/ Division
*= Multiplication with assignment
/= Division with assignment
+ Addition
= Assignment
+= Addition with assignment

비트연산

Operator Description
& Bitwise AND
<< Left shift
&= Bitwise AND with assignment
<<= Left shift with assignment
| Bitwise inclusive OR
>> Right shift
|= Bitwise inclusive OR with assignment
>>= Right shift with assignment
^ Exclusive OR
^= Exclusive OR with assignment

비교연산

Operator Description
== Equality
< Less than
!= Inequality
<= Less than or equal to
&& Logical AND
> Greater than
|| Logical OR
>= Greater than or equal to

포인터 연산 및 그 외 연산자

Operator Description
–> Member selection
, Comma
–>* Pointer-to-member selection
() Function Call
[] Index

Example

#include <iostream>

class Number
{
private:
    int val;
public:
    Number(int val)
    {
        this->val = val;
    }
    Number operator + (int val)
    {
        printf("%d\n", this->val + val);
        return Number(this->val + val);
    }
    Number operator + (Number num)
    {
        printf("%d\n", this->val + num.val);
        return Number(this->val + num.val);
    }

    int getValue()
    {
        return val;
    }
};

int main(int argc, char** argv)
{
    Number num(20);

    printf("%d\n", (num+20+5+Number(30)).getValue());
    return 0;
}
40
45
75
75

상수와 Number 클래스를 섞어서 덧셈을 계산하는 예제입니다.

위 코드에서는 rhs 로 int 를 받는 경우와 Number 클래스를 받는 경우 모두 Number 클래스가 리턴되며, lhs 는 항상 Number 클래스여야 합니다.

  • int 가 lhs 에 위치하는 경우는 오버로딩 하지 않았습니다.
num+20+5+Number(30)

먼저 우선순위가 높은 연산자 중에 연산이 가능한 부분을 찾습니다.

  • num+5 는 lhs 가 Number, rhs 가 int 이므로 연산이 가능합니다. 연산 후 식은 Number(40)+5+Number(30)이 됩니다.

같은 원리로, Number(45)+Number(30)이 되고, lhs 가 Number, rhs 가 Number 이므로 연산할 수 있습니다.
모든 연산을 마친 값은 Number(75)가 됩니다.

이 블로그는 개인 블로그입니다. 게시글은 오류를 포함하고 있을 수 있지만, 저자는 오류를 해결하기 위해 노력하고 있습니다.
게시글에 별도의 고지가 없는 경우, 크리에이티브 커먼즈 저작자표시-비영리-변경금지 4.0 라이선스를 따릅니다.

This blog is personal blog. published posts may contain some errors, but author doing efforts to clear errors.
If post have not notice of license, it under creative commons Attribution-NonCommercial-NoDerivatives 4.0.