Notice
Recent Posts
Recent Comments
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

SYDev

C++ Chapter 10-3 : 교환법칙 문제의 해결 본문

Programming Lang/C++

C++ Chapter 10-3 : 교환법칙 문제의 해결

시데브 2023. 7. 24. 20:46

자료형이 다른 두 피연산자를 대상으로 하는 연산

 연산자 오버로딩을 이용하면 다음 예제와 같이 서로 다른 자료형의 두 데이터간의 연산이 가능해진다.

#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*(int times)
    {
        Point pos(xpos*times, ypos*times);
        return pos;
    }
};

int main(void)
{
    Point pos(1, 2);
    Point cpy;

    cpy=pos*3;
    cpy.ShowPosition();

    cpy=pos*3*2;
    cpy.ShowPosition();
    
    return 0;
}
[3, 6]
[6, 12]

 하지만 곱셈연산에서 성립되는 교환법칙이 위와 같은 예제에서는 적용되지 않는다. 

 

 이런 교환법칙이 성립하려면, 다음 곱셈 연산이 가능해야 한다.

cpy = 3*pos;

 위 연산이 가능하려면 연산자는 다음과 같이 해석되어야 한다.

cpy = operator*(3, pos)

 이게 가능하려면 함수를 전역함수 형태로  오버로딩해야 한다.

 

 위 방법으로 예제를  확장해보자.

#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*(int times)
    {
        Point pos(xpos*times, ypos*times);
        return pos;
    }
    friend Point operator*(int times, Point &ref);
};

Point operator*(int times, Point &ref)
{
    Point pos(ref.xpos * times, ref.ypos * times);
    return pos;
}

int main(void)
{
    Point pos(1, 2);
    Point cpy;

    cpy=3*pos;
    cpy.ShowPosition();

    cpy=3*pos*2;
    cpy.ShowPosition();
    
    return 0;
}
[3, 6]
[6, 12]

 


출처 : 윤성우, <윤성우의 열혈 C++ 프로그래밍>, 오렌지미디어, 2010.05.12