인프런 커뮤니티 질문&답변
[연습문제] 이니셜라이저 리스트 , 대입연산자 오버로딩
해결된 질문
작성
·
411
2
안녕하세요?
이 경우에는 파라미터?로 이니셜라이저 리스트를 받으니까
1. 셀프 어사인먼트 방지하는 방법은 생각을 못했습니다.
IntArray& operator=(const std::initializer_list<int>& list)
{
cout << "assignment operator" << endl;
cout << "list.size() In assignment operator " << list.size() << endl;
delete[] m_data;
int length = list.size();
m_data = new int[length];
int count = 0;
for (auto& element : list)
{
m_data[count] = element;
++count;
}
return *this;
}
//IntArray(list.size()); // 생성자를 통한 초기화는 안되는거고
2. m_data가 데이터를 가지고 있을 수는 있으니까 지워주고 리스트의 길이만큼 new로 초기화해주고
리스트의 값을 복사해줬습니다.
교재인 learncpp에서 해당 부분을 찾아보니 다음과 같이 출력을 해야 한다더라고요.

그런데 리스트의 사이즈는 7인데 5개만 나왔습니다. 자고 일어나서 해결해보겠습니다.
감사합니다.
<출력화면>

<전체코드>
// 9_12.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <cassert>
#include <initializer_list>
using namespace std;
class IntArray
{
private:
unsigned m_length = 0;
int* m_data = nullptr;
public:
IntArray(unsigned length = 0)
: m_length(length)
{
m_data = new int[length];
}
IntArray(const std::initializer_list<int>& list)
: IntArray(list.size())
{
cout << "list.size() In constructor " << list.size() << endl;
int count = 0;
for (auto& element : list)
{
m_data[count] = element;
++count;
}
//for (unsigned count = 0; count < list.size(); ++count)
// m_data[count] = list[count]; // error
}
~IntArray()
{
delete[] this->m_data;
}
IntArray& operator=(const std::initializer_list<int>& list)
{
cout << "assignment operator" << endl;
cout << "list.size() In assignment operator " << list.size() << endl;
delete[] m_data;
int length = list.size();
m_data = new int[length];
int count = 0;
for (auto& element : list)
{
m_data[count] = element;
++count;
}
return *this;
}
friend std::ostream& operator << (std::ostream& out, const IntArray& arr)
{
for (unsigned i = 0; i < arr.m_length; ++i)
out << arr.m_data[i] << " ";
out << endl;
return out;
}
};
int main()
{
int my_arr1[5] = { 1,2, 3,4,5 };
int* my_arr2 = new int[5]{ 1,2,3,4,5 };
auto il = { 10, 20, 30 };
IntArray int_array { 1, 2, 3, 4, 5 };
cout << int_array << endl;
int_array = {7, 2, 3, 2, 1, 6, 5};
cout << int_array << endl;
return 0;
}





