Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ structs defined in header and implemented in cpp

How can i make sure that the somecolor that i implement keeps his value when you use it in another class?

struct.h

struct Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};
Color someColor;
//if i define the color here it says...:
Color someColor = {255,255,255}; //error: data member inializer not allowed

struct.cpp

struct::Color someColor = {255,255,255};

someotherclass.cpp

struct *str = new struct();
str->someColor.r //is not the correct value /not set
like image 586
Sebastiaan van Dorst Avatar asked Dec 08 '22 16:12

Sebastiaan van Dorst


1 Answers

You need to declare it in the header:

extern Color someColor;

and define it in the .cpp file:

Color someColor = {255, 255, 255};

Side note, your syntax struct::Color is highly misleading. It's parsed as struct ::Color, and in C++ terms, it's equivalent to ::Color or just Color (unless you're inside a namespace).

like image 151
Angew is no longer proud of SO Avatar answered Dec 11 '22 05:12

Angew is no longer proud of SO