+ 3

How can I use a struct array In a class? C++?

Maybe this is a dumb questions but, how can I use a struct array in a class? Class Products { Private: Struct s_products { String name; Int code; }; s _products product[100]; }; Is this the right way to declare a struct array inside a class If I want to have 100 products where contains 100 names and 100 codes?

1st Feb 2019, 9:17 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
3 Réponses
+ 4
There are a few ways to do it. You can either declare the struct outside the class, and declare an array of that struct inside the class: struct product { // struct members }; class Products { product prod_arr[100]; }; or you can define the struct array with the struct definition directly, creating an unnamed struct. class Products { struct { // struct members } prod_arr[100]; };
2nd Feb 2019, 2:44 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
you can also use constructor inside an structure and use that to manipulation. struct Point { int x; int y; }; It is also possible to add a constructor (this allows the use of Point(x, y) in expressions): struct Point { int x; int y; Point(int ax, int ay): x(ax), y(ax) {} }; Point can also be parametrized on the coordinate type: template<typename Coordinate> struct point { Coordinate x, y; };   // A point with integer coordinates Point<int> point1 = { 3, 5 };   // a point with floating point coordinates Point<float> point2 = { 1.7, 3.6 }; Of course, a constructor can be added in this case as well.
2nd Feb 2019, 9:27 AM
MsJ
MsJ - avatar