I initialize the array in the structure directly:
struct Array { int arr3[3]; }; Array ar = { 1, 2, 3}; how to initialize ar with an already created array
int as[3] = { 1, 2, 3 }; Array ar = ->?as?<- ; I initialize the array in the structure directly:
struct Array { int arr3[3]; }; Array ar = { 1, 2, 3}; how to initialize ar with an already created array
int as[3] = { 1, 2, 3 }; Array ar = ->?as?<- ; What you use in the example is called an aggregate initialization (see clause 8.5.1. Of the Standard).
To initialize an Array already created array, you can write this:
int a[3] = { 1, 2, 3 }; Array ar = { a[0], a[1], a[2] }; This is not very expressive, but it does not require changing the Array class. If you add a constructor, you can make initialization more beautiful (however, the class will no longer be trivial, and aggregate initialization will not be possible):
struct Array { int arr3[3]; Array( int(&a)[3] ) : arr3 { a[0], a[1], a[2] } {} // добавили конструктор }; int a[] = { 1, 2, 3 }; Array ar = a; // теперь это работает Array ar2 = { 1, 2, 3 }; // а это перестало работать To ensure at the same time the possibility of initialization as in the original example, you will have to add another constructor:
Array( int a0, int a1, int a2 ) : arr3 { a0, a1, a2 } {} There is a clever way :) - if these arrays, like yours, are hidden in structures.
In this case , the copy constructor is called [by default, if you have not defined your own]. So that
struct Array { int a[3]; }; Array a = {1, 2, 3}; Array b = a; will work. In the case of simple arrays, you need to copy.
Source: https://ru.stackoverflow.com/questions/509019/
All Articles
int arr3[3];writeint* arr3;and then assign it a pointer to the array created and initialized separately. - Andrey Kuruljov