Initialize object containing c-style array as member variable (c++)

  • A+
Category:Languages

Consider following code:

struct Color  //this struct can't be modified {     double grey;     double rgb[3]; };  int main() {     double myRGB[3] = {2, 6, 9};      Color c = {10, myRGB}; //this line doesn't work      return 0; } 

How can I initialize a Color object in one line? In my real case scenario, Color struct can't be change (for example to use std::array instead of C-Style array).

 


Since Color is an aggregate you can use aggregate initialization and put the array initializer directly in the braces like

Color c = {10, {2, 6, 9}}; 

If you have to initialize c with an array, since it is small, you can just unroll it like

Color c = {10, {myRGB[0], myRGB[1], myRGB[2]}}; 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: