Project Hub

9. 전위/후위 증감 연산자 오버로딩 & 첨자 연산자 오버로딩 본문

C++/c++ basic

9. 전위/후위 증감 연산자 오버로딩 & 첨자 연산자 오버로딩

safy 2022. 12. 21. 13:46
728x90
반응형

이전 글

2022.12.21 - [C++/c++ basic] - 8. 입출력 연산자 오버로딩

 

8. 입출력 연산자 오버로딩

이전 글 2022.12.21 - [C++/c++ basic] - 7. 이항 연산자 오버로딩 7. 이항 연산자 오버로딩 이전 글 2022.12.21 - [C++/c++ basic] - 6. Wrapper 클래스 - 타입변환 연산자 6. Wrapper 클래스 - 타입변환 연산자 이전 글 &

projecthub.tistory.com

참고 글

2022.12.21 - [C++/c++ basic] - 5. 연산자 오버로딩, friend 키워드

 

5. 연산자 오버로딩, friend 키워드

이전 글 2022.12.21 - [C++/c++ basic] - 4. implicit, explicit, mutable 키워드 4. implicit, explicit, mutable 키워드 이전 글 2022.12.21 - [C++/c++ basic] - 3. copy consturctor 3. copy consturctor 이전 글 2022.12.21 - [C++/c++ basic] - 2. refer

projecthub.tistory.com

 


1. 전위/후위 연산자 오버로딩

 

C++ 에서 전위/후위 연산자들을 구분하는 방법은 아래와 같다.

// 전위 증감 연산자
operator++();
operator--();
 
// 후위 증감 연산자
operator++(int);
operator--(int);

 

전위/후위 연산자에 대한 오버로딩 구현을 다음과 같다.

#include <iostream>
 
class CSample
{
public:
    int iValue;
 
public:
    CSample(int iValue) : iValue(iValue) {}
    CSample(const CSample& sample) : iValue(sample.iValue) {}
 
    CSample& operator++()
    {
        iValue++;
        std::cout << "전위 증감 연산자" << std::endl;
         
        return *this;
    }
 
    CSample operator++(int)
    {
        CSample temp(*this);
       iValue++;
        std::cout << "후위 증감 연산자" << std::endl;
         
        return temp;
    }
 
    void func(const CSample& sample)
    {
        std::cout << "iValue : " << iValue << std::endl;
    }
};
 
int main()
{
    CSample sample(3);
 
    func(++sample);
    func(sample++);
 
    std::cout << "iValue : " << sample.iValue << std::endl;
}

 

2. 첨자 연산자 오버로딩

배열에 원소를 지정할 때 사용되는 첨자 연산자 [] 를 오버로딩 하는 방법.

char& operator[](const int index);
...
char& MyString::operator[](const int index)
{
    return m_String[index];
}
...
str[1] = 'b';
...





728x90
반응형

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

11. virtual 함수와 다형성  (0) 2022.12.21
10. 업 캐스팅 & 다운 캐스팅  (0) 2022.12.21
8. 입출력 연산자 오버로딩  (1) 2022.12.21
7. 이항 연산자 오버로딩  (2) 2022.12.21
6. Wrapper 클래스 - 타입변환 연산자  (0) 2022.12.21
Comments