-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
해결됨
질문입니다
21.06.06 00:41 작성 조회수 96
0
안녕하세요
// 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;
}
이 코드에서 operator = 에 사이즈 7로 잘들어가는데
cout << int_array<<endl; 마지막줄을 실행시킬때
5개만 나오는데 왜그런지 모르겠습니다 ㅜㅜ
그리고 initializer_list 를 왜사용해랴하는지도 정확하게 알지못하겠습니다 ㅜ
답변을 작성해보세요.
6
안소
2021.06.07
1. 출력 연산자 오버로딩 된 내용을 보면 m_length 만큼 반복문을 도는데, = 연산자 오버로딩 내용을 보면 m_length 는 업데이트를 안하셨어요~ m_data 에 7개 원소를 대입하기만 하셨지 m_length 멤버 변수는 7로 업데이트 하지 않으셨습니다. 그러니 m_length 는 5 인 상태로 변함이 없었기 때문에 출력 연산자에서 반복문 5 번만 돈 것입니다. 일반 int length 변수을 사용하셨는데,
이렇게 하셔야하지 않을까 싶습니다. 디버깅 하면 왜 이런 결과가 나온건지 그 원인을 쉽게 추적하실 수 있습니다. 공부하실 때, 코드 짜실 때 디버깅 꼭 해보시길 바랍니다.
2. 컨테이너 초기화 하기 편하기 때문입니다. 코드에서도 볼 수 있다시피 파라미터로 넘긴 initializer_list 타입의 list 에서 size() 함수를 호출해서 {7, 2, 3, 2, 1, 6, 5} 의 사이즈가 뭔지도 바로 알 수 있었죠. 이처럼 initializer_list 는 c++ 에 정의된 클래스 타입이기 때문에 size(), begin(), end() 등의 멤버 함수 호출로 컨테이너 정보에 대해 쉽게 알 수도 있구요. 만약 이 파라미터를 배열로 넘겼다면 이 배열의 사이즈를 알기 위해선 또 반복문 일일이 돌리면서 세었어야 겠죠? 이 때문에 뒤에서 배우실 C++ STL 의 여러 컨테이너들은 이 initializer_list 를 사용하여 만들어진 경우가 많습니다.
https://stackoverflow.com/questions/39512381/why-do-we-use-initializer-list-in-c11
링크 참고 해주세요.
답변 1