| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 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 | 29 | 
| 30 | 
                            Tags
                            
                        
                          
                          - PCA
 - AI
 - supervised learning
 - LG Aimers
 - 오블완
 - LG Aimers 4th
 - 머신러닝
 - deep learning
 - Machine Learning
 - LG
 - gpt
 - 해커톤
 - 지도학습
 - 분류
 - 티스토리챌린지
 - regression
 - ChatGPT
 - Classification
 - LLM
 - 딥러닝
 - 회귀
 - GPT-4
 - OpenAI
 
                            Archives
                            
                        
                          
                          - Today
 
- Total
 
SYDev
C++ Chapter 10-3 : 교환법칙 문제의 해결 본문
자료형이 다른 두 피연산자를 대상으로 하는 연산
연산자 오버로딩을 이용하면 다음 예제와 같이 서로 다른 자료형의 두 데이터간의 연산이 가능해진다.
#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
728x90
    
    
  반응형
    
    
    
  'Programming Lang > C++' 카테고리의 다른 글
| C++ Chapter 10-4 추가 내용 (버퍼, fflush 함수) (0) | 2023.07.25 | 
|---|---|
| C++ Chapter 10-4 추가 내용 (함수 포인터) - 미해결 (0) | 2023.07.25 | 
| C++ Chapter 10-2 : 단항 연산자의 오버로딩 (1) | 2023.07.24 | 
| C++ Chapter 04-4 추가 내용 (0) | 2023.07.24 | 
| C++ Chapter 10-1 : 연산자 오버로딩의 이해와 유형 (0) | 2023.07.23 |