This will do it:
#include <array>
class obj{
int x;
public:
obj(int n) {x=n;}
};
int main()
{
std::array<obj,3> p = {3, 7, 11};
}
std::array gives you same semantics as a primitive array type but qualifies as a c++ container. You would probably be better off using std::vector, which offers dynamic re-sizing and more protection:
#include <vector>
...
std::vector<obj> p = {obj(1), obj(2), obj(4)};
The nice thing about using generic containers is you can often use them interchangably:
#include <vector>
//#include <array>
#include <algorithm>
...
int main()
{
std::vector<obj> p = {obj(1), obj(2), obj(4)};
// or the following:
// std::array<obj,3> p = {obj(1), obj(2), obj(4)};
// either one of the above will work here
std::for_each(begin(p), end(p),
[](obj const & o){ std::cout << o.x << " "; });
std::cout << std::endl;
// ^^^ yes, this only works if x is public
}
Note that std::array is sized at compile time so it does require that you tell it the number of elements.
You could also rewrite the original class to use initializer list construction as follows:
class obj{
int x;
public:
obj(int n) : x(n) { }
};
Even in this example it might help because it allows you to make x
const
. In general it has a lot of benefits and is a good habit to get into.