본문 바로가기

Native/C++

Overloading operator function

[code]#include <turboc.h>

class position
{
private:
    int x, y;
    char ch;
    // mutable은 상수 멤버 함수나 객체의 상수성을 완전히 무시해
    // 버린다 변수는 본질적으로 값을 마음대로 바꿀 수 있지만
    // const 에 의해 값 변경이 금지 된다. mutable은 이런 const
    // 의 값 변경 금지 기능을 금지하여 값 변경을 다시 허용하자는
    // 복잡한 지정을 한다
    mutable char info[256];
    
public:
    position(int ax, int ay, char ach)
    {
        x = ax;
        y = ay;
        ch = ach;
    }
    void outPosition() const
    {
        gotoxy(x, y);
        putch(ch);
    }
    void moveTo(int ax, int ay)
    {
        x = ax;
        y = ay;
    }

    // operator function
    bool operator ==(const position &target) const
    {
        return (x==target.x && y==target.y);
    }

    bool operator !=(const position &target) const
    {
        return !(*this == target);
    }

    // y 좌표를 최우선 비교하고 y가 같을 경우는 x 좌표로 비교하되 ch는 출력할 문자이므로 비교 대상에서 제외하는 것으로 정의한다
    bool operator >(const position &target) const
    {
        if(y > target.y)
            return true;
        else if (y == target.y)
        {
            if (x > target.x)
                return true;
            else
                return false;
        }
        else
            return false;
    }

    bool operator >=(const position &target) const
    {
        return (*this == target || *this > target);
    }

    bool operator <(const position &target) const
    {
        return !(*this >= target);
    }

    bool operator <=(const position &target) const
    {
        return !(*this > target);
    }

    void makeInfo() const
    {
        sprintf(info, "x=%d, y=%d, ch=%c\n", x, y, ch);
    }

    void outInfo() const
    {
        puts(info);
    }
};

void main()
{
    const position here(11, 22, 'Z');
    here.makeInfo();
    here.outInfo();
}

//////////////////////////////////////////////////////////////////////////////////////////////////

1. Search "class position"


// operator function
bool operator ==(const position &target) const
{
    return (x==target.x && y==target.y);
}

bool operator !=(const position &target) const
{
    return !(*this == target);
}

// y 좌표를 최우선 비교하고 y가 같을 경우는 x 좌표로 비교하되 ch는 출력할 문자이므로 비교 대상에서 제외하는 것으로 정의한다
bool operator >(const position &target) const
{
    if(y > target.y)
        return true;
    else if (y == target.y)
    {
        if (x > target.x)
            return true;
        else
            return false;
    }
    else
        return false;
}

bool operator >=(const position &target) const
{
    return (*this == target || *this > target);
}

bool operator <(const position &target) const
{
    return !(*this >= target);
}

bool operator <=(const position &target) const
{
    return !(*this > target);
}[/code]

'Native > C++' 카테고리의 다른 글

연산자 관련 소스들 (operator)  (0) 2013.10.02
Dumy type operation 대입 연산자  (0) 2013.10.02
전역 연산자 함수  (0) 2013.10.02
연산자 함수 (operator function)  (0) 2013.10.02
revolve  (0) 2013.10.02