#include<cassert> // for assert()#include<iostream>classIntArray{private:intm_length{};int*m_data{};public:IntArray()=default;IntArray(intlength):m_length{length},m_data{newint[length]{}}{}~IntArray(){delete[]m_data;// 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}int&operator[](intindex){assert(index>=0&&index<m_length);returnm_data[index];}intgetLength()const{returnm_length;}};intmain(){// 如果我们使用初始化值列表对IntArray进行初始化会发生什么呢?IntArrayarray{5,4,3,2,1};// 无法编译for(intcount{0};count<5;++count)std::cout<<array[count]<<' ';return0;}
#include<cassert> // for assert()#include<initializer_list> // for std::initializer_list#include<iostream>classIntArray{private:intm_length{};int*m_data{};public:IntArray()=default;IntArray(intlength):m_length{length},m_data{newint[length]{}}{}IntArray(std::initializer_list<int>list)// allow IntArray to be initialized via list initialization:IntArray(static_cast<int>(list.size()))// use delegating constructor to set up initial array{// Now initialize our array from the listintcount{0};for(autoelement:list){m_data[count]=element;++count;}}~IntArray(){delete[]m_data;// 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}IntArray(constIntArray&)=delete;// to avoid shallow copiesIntArray&operator=(constIntArray&list)=delete;// to avoid shallow copiesint&operator[](intindex){assert(index>=0&&index<m_length);returnm_data[index];}intgetLength()const{returnm_length;}};intmain(){IntArrayarray{5,4,3,2,1};// initializer listfor(intcount{0};count<array.getLength();++count)std::cout<<array[count]<<' ';return0;}
#include<cassert> // for assert()#include<initializer_list> // for std::initializer_list#include<iostream>classIntArray{private:intm_length{};int*m_data{};public:IntArray()=default;IntArray(intlength):m_length{length},m_data{newint[length]{}}{}IntArray(std::initializer_list<int>list)// allow IntArray to be initialized via list initialization:IntArray(static_cast<int>(list.size()))// use delegating constructor to set up initial array{// Now initialize our array from the listintcount{0};for(autoelement:list){m_data[count]=element;++count;}}~IntArray(){delete[]m_data;}// IntArray(const IntArray&) = delete; // to avoid shallow copies// IntArray& operator=(const IntArray& list) = delete; // to avoid shallow copiesint&operator[](intindex){assert(index>=0&&index<m_length);returnm_data[index];}intgetLength()const{returnm_length;}};intmain(){IntArrayarray{};array={1,3,5,7,9,11};// Here's our list assignment statementfor(intcount{0};count<array.getLength();++count)std::cout<<array[count]<<' ';return0;}