Minwoo Dev.

[C++] 윤성우의 열혈 C++ 10-2 단항 연산자 오버로딩 문제풀이 본문

C++

[C++] 윤성우의 열혈 C++ 10-2 단항 연산자 오버로딩 문제풀이

itisminu 2024. 5. 12. 09:01
728x90
반응형
SMALL

문제 1 : 멤버함수의 형태로 오버로딩

부호 연산자로서 - 는 단항 연산자이다. 이 연산자는 피연산자의 부호를 반전시킨 결과를 반환한다.

예를 들어서 다음 문장이 실행되면,

int num2 = -num1;

 

num2에는 num1과 절대값은 같지만 부호가 다른 값이 저장된다. 물론 num1의 값에는 영향을 미치지 않는다. 이와 유사하게 Point 클래스를 대상으로 - 연산자를 오버로딩해보자.

다음의 문장이 실행되면,

Point pos2 = -pos1;

 

pos2의 멤버변수는 pos1의 멤버변수 값과 다른 부호의 값으로 초기화되도록 오버로딩해보자.

 

 

정답 

소스코드

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;

public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ", " << ypos << "]" << endl;
    }
    Point operator-()
    {
        Point pos;
        pos.xpos = -this->xpos;
        pos.ypos = -this->ypos;
        return pos;
    }
};

int main(void)
{
    Point pos1(3, 4);
    Point pos2 = -pos1;

    pos1.ShowPosition();
    pos2.ShowPosition();
    return 0;
}

 

실행 결과

 

 


 

문제 2 : 전역함수의 형태로 오버로딩

~연산자는 단항 연산자로서 비트단위 not의 의미를 갖는다.

즉, ~ 연산자는 비트단위로 1은 0으로, 0은 1으로 바꾼다.

이에 우리는 Point 객체를 대상으로 다음과 같이 연산이 가능하도록 ~연산자를 오버로딩 하고자 한다.

Point pos2 = ~pos1;

 

위의 ~연산의 결과로 반환된 객체의 xpos 멤버에는 pos1의 ypos 값이, 반환된 객체의 ypos 멤버에는 pos1의 xpos 값이 저장되어야 한다.

 

 

정답

소스코드

#include <iostream>
using namespace std;

class Point
{
private:
    int xpos, ypos;

public:
    Point(int x = 0, int y = 0) : xpos(x), ypos(y) {}
    void ShowPosition() const
    {
        cout << "[" << xpos << ", " << ypos << "]" << endl;
    }
    friend Point operator~(Point &pos);
};

Point operator~(Point &pos)
{
    Point tmp;
    tmp.xpos = pos.ypos;
    tmp.ypos = pos.xpos;
    return tmp;
}

int main(void)
{
    Point pos1(3, 7);
    Point pos2 = ~pos1;

    pos1.ShowPosition();
    pos2.ShowPosition();
    return 0;
}

 

 

결과

728x90
반응형
LIST