250x250
Notice
Recent Posts
«   2024/07   »
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
관리 메뉴

일상 코딩

[C++/9.06] 첨자"[]" 연산자 오버로딩 본문

C++/따배C++ 09강 연산자 오버로딩

[C++/9.06] 첨자"[]" 연산자 오버로딩

polarcompass 2021. 10. 30. 01:18
728x90
#include<iostream>
#include<cassert>

class IntList
{
private:
    int m_list[10]{1,2,3,4,5,6,7,8,9,10};

public:
    // void setItem(int index, int value)
    // {
    //     m_list[index] = value;
    // }

    // int getItem(int index)
    // {
    //     return m_list[index];
    // }
    // // array 자체를 포인터로 얻는 방법
    // int * getList()
    // {
    //     return m_list;
    // }

    int & operator [] (const int index)
    {
        // 이렇게 assert로 막아줘야 
        // runtime error debugging시 시간을 
        // 아낄 수 있다.
        assert(index >= 0);
        assert(index < 10);

        return m_list[index];
    }

    const int & operator [] (const int index) const // 이 함수 안에서 
    {                                               // 멤버 변수 변경 안한다는 의미

        assert(index >= 0);
        assert(index < 10);

        return m_list[index];
    }
};

int main(int argc, char const *argv[])
{
    // IntList my_list;
    // my_list.setItem(3, 1);
    // std::cout << my_list.getItem(3) << std::endl;
    //         // getList 뒤의 ()괄호가 가독성을 망치므로
    //         // []대괄호 연산자를 정의 해준다.
    // my_list.getList()[3] = 10;
    // std::cout << my_list.getList()[3] << std::endl;

    IntList my_list;
    // my_list[3] = 10;
    std::cout << my_list[3] << std::endl;

    return 0;
}
728x90