컴퓨터 언어/C++

[C++] C++ 15일차 연산자 오버로딩

훈츠 2020. 4. 17. 12:26
반응형

안녕하세요. 훈츠입니다. 금일은 연산자 오버로딩에 관해 포스팅 합니다.


연산자 오버로딩

연산자 오버로딩은, 간략한 표기와 고유의 의미를 유지하여 가독성과 코드 작성을 짧게 할 수 있습니다.

 

  • 기본 연산자의 기능을 객체에도 적용
  • 연산자를 중복해서 정의 하는것
  • 고유 연산자 기능 외에 사용자가 정의한 기능을 연산자로 실행하게 하는 것

형식

  •  리턴형 Operator  연산자 (매개 변수들…)

 

 오버로딩이 불가능한 연산자

  • . (멤버 선택시 사용하는 dot) , .* , ?:, sieof
  • :: (범위 한정 연산자)

 

오버로딩 예시

  1. 이항 연산자인 사칙 연산자
  2. 단항 연산자인 증가 연산자 ++ (전치형, 후치형)

코드1

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
31
32
33
34
35
36
class A
{
private: int mVar;
public:
    int operator +(A& refA) {
        return mVar + refA.mVar;
    }
    int operator -(A& refA) {
        return mVar - refA.mVar;
    }
    int operator *(A& refA) {
        return mVar * refA.mVar;
    }
    int operator /(A& refA) {
        return mVar / refA.mVar;
    }
    int Get() {
        return mVar;
    }
    A(int nVar) : mVar(nVar) {}
};
 
int main()
{
    A t1(20), t2(10);
    cout << "+ 연산자 오버로딩 " << t1 + t2 << endl;
    cout << "- 연산자 오버로딩 " << t1 - t2 << endl;
    cout << "* 연산자 오버로딩 " << t1 * t2 << endl;
    cout << "/ 연산자 오버로딩 " << t1 / t2 << endl;
 
    cout << "T1 GET  " << t1.Get() << endl;
    cout << "T2 GET  " << t2.Get() << endl;
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

코드2

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
class B
{
private: int mVar;
public:
    void operator ++() {
        ++mVar;
        cout << "전치 ++ 호출 : "<< mVar << endl;
    }
    void operator ++(int i) {
        mVar++;
        cout << "후치 ++ 호출: " << mVar << endl;
    }
    void Print() { cout << mVar << endl; }
    B(int nVar) : mVar(nVar) {};
 
};
 
int main()
{
    B test(1);
    ++test;
    test++;
 
    return 0;
}
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

 

 

반응형