Initializing non-aggregate

I have a class with an array(public) and a private member.
When I initialize the array of the object of the class, it gives an error.
non-aggregate can't be initialized...something like this.

That private member is causing the problem.

I found a solution initializing the members one by one, but that makes the code long.

Is there any way to initialize the array in one row?



1
2
3
4
5
6
7
8
class array
{
public:
	int A[n];
	array();
private:
	int x;
};
There are C++11 solutions, e.g.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <algorithm>
#include <iostream>
#include <initializer_list>
const std::size_t n = 5;

class array
{
public:
    int A[n];
    array(std::initializer_list<int> il) : A{}
    {
        std::copy(il.begin(), il.begin() + std::min(n, il.size()), A);
    }
private:
    int x;
};

int main()
{
    array a = {1,2,3};
    std::cout << "The array contents are: ";
    for(int n: a.A)
        std::cout << n << ' ';
}

demo: http://coliru.stacked-crooked.com/a/d70aec0d8de2a5ef

although it would work better if array were a class template, such as tempalte<size_t n> class array { ...
Topic archived. No new replies allowed.