I am working on editing some old C++ code that uses global arrays defined like so:
int posLShd[5] = {250, 330, 512, 600, 680};
int posLArm[5] = {760, 635, 512, 320, 265};
int posRShd[5] = {765, 610, 512, 440, 380};
int posRArm[5] = {260, 385, 512, 690, 750};
int posNeck[5] = {615, 565, 512, 465, 415};
int posHead[5] = {655, 565, 512, 420, 370};
I want to make all of these arrays private members of the Robot class defined below. However, the C++ compiler does not let me initialize data members when I declare them.
class Robot
{
private:
int posLShd[5];
int posLArm[5];
int posRShd[5];
int posRArm[5];
int posNeck[5];
int posHead[5];
public:
Robot();
~Robot();
};
Robot::Robot()
{
// initialize arrays
}
I want to initialize the elements of these six arrays in the Robot() constructor. Is there any way to do this other than assigning each element one by one?
If your requirement really permits then you can make these 5 arrays as
staticdata members of your class and initialize them while defining in .cpp file like below:If that is not possible then, declare this arrays as usual with different name and use
memcpy()for data members inside your constructor.Edit:
For non static members, below
templatestyle can be used (for any type likeint). For changing the size, simply overload number of elements likewise:C++11
The array initialization has now become trivial: