Qaupot Blog
Software Engineering, Trip

302. 1항 (단항) 연산자

🕐 Thu, 20 Feb 2014 09:00:00 GMT 🕓 Tue, 31 Aug 2021 12:55:00 GMT

1항(단항, unary) 연산자 오버로딩

1항 연산자에서 오버로딩이 가능한 연산자는 다음과 같습니다.

Operator Description
! Logical not
& Address
~ One's complement
* Pointer dereference (포인터 역참조)
+ Unary plus
Unary minus
++ Increment
–– Decrement
conversion operators

1항 연산자는 자기 자신을 항으로 사용하기 때문에 클래스 멤버로 선언할 때는 별도의 추가 인수가 필요하지 않습니다. 그러나, 전역에 선언할 경우 적용될 자료형 인수를 하나 지정합니다.

객체지향 패러다임에서는 '전역 (global)'이라는 개념은 약하기 때문에, 전역 단위의 연산자 오버로딩은 피하는게 좋습니다.

#include <iostream>

class Number
{
private:
    int val;
public:
    Number(int val)
    {
        this->val = val;
    }
    Number operator + ()
    {
        return *this;
    }
    Number operator - ()
    {
        return Number(-val);
    }
    Number* operator &()
    {
        return this;
    }
    Number operator *()
    {
        return *this;
    }

    int getValue()
    {
        return val;
    }
};

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

    printf("%d\n", (-num).getValue());
    printf("%d\n", (num).getValue());
    printf("%d\n", (*num).getValue());
    printf("%x\n", &num);
    return 0;
}
-20
20
20
ddfcb8 (현재 인스턴스의 주소)

1항 연산자는 자주 사용되면서도 치명적인 연산자가 있어서, 오버로딩시 특히 주의해야합니다.

  • 주소 값을 구하는 &를 오버로딩하고, 다른 의미로 사용했다면 이후 주소 값을 구할 수 없습니다.
  • 포인터 역참조의 경우에는 포인터 변수가 아닌 이상 별다른 의미가 없습니다.

연산자는 비교적 자유롭게 활용할 수 있으며, 클래스로 포인터와 비슷한 스마트 포인터를 설계하여 쓰기도 합니다.

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