13.5 Overloading operators using member functions

주홍영·2022년 3월 18일
0

Learncpp.com

목록 보기
148/199

https://www.learncpp.com/cpp-tutorial/overloading-operators-using-member-functions/

우리는 지난 섹션에서 friend function과 normal function으로 operator overloading하는 것에 대해서 배웠다

Member function으로 operator overloading하는 것 또한 friend와 매우 유사하다

참고로 지켜야할 몇가지 규칙이 있다

  • left operand가 될 타입의 클래스에 정의되어야 한다는 것이다
  • 여기서 left operand는 implicit하게 *this object가 된다
  • 다른 operand는 function의 parameter가 된다
#include <iostream>

class Cents
{
private:
    int m_cents {};

public:
    Cents(int cents)
        : m_cents { cents } { }

    // Overload Cents + int
    Cents operator+ (int value);

    int getCents() const { return m_cents; }
};

// note: this function is a member function!
// the cents parameter in the friend version is now the implicit *this parameter
Cents Cents::operator+ (int value)
{
    return Cents { m_cents + value };
}

int main()
{
	Cents cents1 { 6 };
	Cents cents2 { cents1 + 2 };
	std::cout << "I have " << cents2.getCents() << " cents.\n";

	return 0;
}

위의 코드를 보면 이항 연산자 이나 클래스 내부에서 member functionㅇ로 선언될 때
파라미터가 하나인 것을 알 수 있다

그리고 define할 때
Cents Cents::operator+ (int value)
{}
와 같이 return type과 Cents의 member function을 정의하는 것과 같이 ::을 통해서 접근한다

Not everything can be overloaded as a friend function

The assignment (=), subscript ([]), function call (()), and member selection (->) operators 는 반드시 member functiond으로 정의되어야 한다
왜냐하면 c++이 그렇게 요구하기 때문이다

Not everything can be overloaded as a member function

operator<<와 >>의 경우에는 member로 정의될 수 없다
왜냐하면 member function으로 정의할 경우 클래스 타입이 반드시 left operand가 되어야 하기 때문에 위의 operator는 overlaoding이 불가능하다

When to use a normal, friend, or member function overload

대부분의 경우 c++이 너에게 선택을 맡긴다 하지만 더 나은 선택지는 존재한다

When dealing with binary operators that don’t modify the left operand (e.g. operator+), the normal or friend function version is typically preferred, because it works for all parameter types (even when the left operand isn’t a class object, or is a class that is not modifiable). The normal or friend function version has the added benefit of “symmetry”, as all operands become explicit parameters (instead of the left operand becoming *this and the right operand becoming an explicit parameter).

해석
binary operator중에서 left operand를 수정하지 않는 경우 normal friend가 선호된다
왜나하면 모든 parameter type가 함께 다뤄져야하기 때문에
normal friend의 경우 symmetry를 제공한다 반면에 member function의 경우 left operand가 클래스가 되어야 한다는 제약이 존재하기에 symmetry가 성립하지 않는다
따라서 1+m1 + 2 + m2 + m3 + 4; 와 같은 chain 연산이 일반 타입으로 시작한다면 불가능하다

When dealing with binary operators that do modify the left operand (e.g. operator+=), the member function version is typically preferred. In these cases, the leftmost operand will always be a class type, and having the object being modified become the one pointed to by *this is natural. Because the rightmost operand becomes an explicit parameter, there’s no confusion over who is getting modified and who is getting evaluated.

해석
만약 left operand를 수정하게 되는 (ex +=)와 같은 operator의 경우 member version이 선호된다. 이러한 경우 leftmost operand는 항사 class type이 되기 때문이고 object가 수정되기 때문이다. 따라서 어떠한 operand가 수정되는지 명확하기에 이런 경우에는 member vesion을 사용한다

Unary operators are usually overloaded as member functions as well, since the member version has no parameters.

해석
단항 연산자의 경우 일반적으로 member version으로 구현된다 왜냐하면 member version은 파라미터가 없기 때문이다

The following rules of thumb can help you determine which form is best for a given situation:
다음의 rules of thumb(경험 법칙)은 주어진 상황에 가장 적합한 형식을 결정하는 데 도움이 될 수 있습니다.

  • If you’re overloading assignment (=), subscript ([]), function call (()), or member selection (->), do so as a member function.
  • If you’re overloading a unary operator, do so as a member function.
  • If you’re overloading a binary operator that does not modify its left operand (e.g. operator+), do so as a normal function (preferred) or friend function.
  • If you’re overloading a binary operator that modifies its left operand, but you can’t add members to the class definition of the left operand (e.g. operator<<, which has a left operand of type ostream), do so as a normal function (preferred) or friend function.
  • If you’re overloading a binary operator that modifies its left operand (e.g. operator+=), and you can modify the definition of the left operand, do so as a member function.
profile
청룡동거주민

0개의 댓글