강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

호두님의 프로필 이미지
호두

작성한 질문수

홍정모의 따라하며 배우는 C++

9.6 첨자 연산자 오버로딩 하기

[09:33] 우리가 만든 클래스IntList의 배열을 선언하기위해 메모리를 동적할당받을 때

해결된 질문

작성

·

186

0

<code>

IntList *list = new IntList;

    // list[3] = IntList; //리스트의 array이기 때문에 다른 문제가 된다라는거
    (*(list + 0))[3] = 22;
    cout << (list[0])[3] << endl;

주석 부분은 IntList의 배열이기 때문에 list[3] 이렇게 접근하는 건 의도가 다르다고 말씀하신 것으로 이해했습니다.

(*(list + 0))[3] = 22;
    cout << (list[0])[3] << endl;

저렇게 쓰려고할 때는 list[3] 이 아니라 위와같이 접근하면 되는거죠?

<전체코드>

#include <iostream>
#include <cassert>

using namespace std;

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

public:
    int & operator []  (const int index)
    {
        assert(index >= 0);
        // assert(index < sizeof(m_list) / sizeof(m_list[0]));
        assert(index < 10);

        return m_list[index];
    }

    const int & operator []  (const int indexconst
    {
        assert(index >= 0);
        assert(index < 10);
        return m_list[index];
    }
    // void setItem(int index, int value)
    // {
    //     m_list[index] = value;
    // }

    // int getItem(int index)
    // {
    //     return m_list[index];
    // }

    // int * getList()
    // {
    //     return m_list;
    // }
};

int main()
{
    IntList *list = new IntList;

    // list[3] = IntList; //리스트의 array이기 때문에 다른 문제가 된다라는거
    (*(list + 0))[3] = 22;
    cout << (list[0])[3] << endl;

    // IntList my_list;
    // my_list[9] = 12;    //lvalue 여야 하니까 참조로 리턴
    // my_list[8] = 6;    //lvalue 여야 하니까 참조로 리턴
    // cout << my_list[9] << endl;
    // cout << my_list[8] << endl;

    // IntList my_list;
    // my_list.setItem(3, 1);
    // cout << my_list.getItem(3) << endl;
    // my_list.getList()[3] = 10;
    // cout << my_list.getList()[3] << endl;

    return 0;
}

감사합니다.

답변 1

1

홍정모님의 프로필 이미지
홍정모
지식공유자

문법상으로는 가능합니다. 아마 주소 체크도 해보셨을 거라고 생각이 되네. 다만 실무에서는 클래스를 만들어서 저렇게 복잡한 indirection을 피하고 보기 좋은 코드를 만드는 것이 보통입니다. 

호두님의 프로필 이미지
호두

작성한 질문수

질문하기