Inflearn Community Q&A
[09:33] 우리가 만든 클래스IntList의 배열을 선언하기위해 메모리를 동적할당받을 때
Resolved
Written on
·
183
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]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
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 index) const
{
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;
}
감사합니다.
C++
Answer 1
1
honglab
Instructor
문법상으로는 가능합니다. 아마 주소 체크도 해보셨을 거라고 생각이 되네. 다만 실무에서는 클래스를 만들어서 저렇게 복잡한 indirection을 피하고 보기 좋은 코드를 만드는 것이 보통입니다.





