initializer_list可以让我们像数组初始化列表一样初始化我们的类。

编译器遇到一个初始化列表时,首先会将其转换成为一个std::initializer_list. 所以在创建我们的类的时候,我们创建一个构造函数,该构造函数是以std::initializer_list作为参数,那么我们就可以使用初始化列表作为输入的参数。

std::initializer_list
header:

  1. #include <cassert> // for assert()
  2. #include <initializer_list> // for std::initializer_list
  3. #include <iostream>
  4. class IntArray
  5. {
  6. private:
  7. int m_length{};
  8. int *m_data{};
  9. public:
  10. IntArray() = default;
  11. IntArray(int length) :
  12. m_length{ length },
  13. m_data{ new int[length]{} }
  14. {
  15. }
  16. IntArray(std::initializer_list<int> list) : // allow IntArray to be initialized via list initialization
  17. IntArray(static_cast<int>(list.size())) // use delegating constructor to set up initial array
  18. {
  19. // Now initialize our array from the list
  20. int count{ 0 };
  21. for (auto element : list)
  22. {
  23. m_data[count] = element;
  24. ++count;
  25. }
  26. }
  27. ~IntArray()
  28. {
  29. delete[] m_data;
  30. // we don't need to set m_data to null or m_length to 0 here, since the object will be destroyed immediately after this function anyway
  31. }
  32. IntArray(const IntArray&) = delete; // to avoid shallow copies
  33. IntArray& operator=(const IntArray& list) = delete; // to avoid shallow copies
  34. int& operator[](int index)
  35. {
  36. assert(index >= 0 && index < m_length);
  37. return m_data[index];
  38. }
  39. int getLength() const { return m_length; }
  40. };
  41. int main()
  42. {
  43. IntArray array{ 5, 4, 3, 2, 1 }; // initializer list
  44. for (int count{ 0 }; count < array.getLength(); ++count)
  45. std::cout << array[count] << ' ';
  46. return 0;
  47. }

Reference

https://www.learncpp.com/cpp-tutorial/stdinitializer_list/