Seb*_*rst 4 c++ implementation struct
当我在另一个类中使用它时,我如何确保我实现的某些颜色保持其价值?
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
Run Code Online (Sandbox Code Playgroud)
struct.cpp
struct::Color someColor = {255,255,255};
Run Code Online (Sandbox Code Playgroud)
someotherclass.cpp
struct *str = new struct();
str->someColor.r //is not the correct value /not set
Run Code Online (Sandbox Code Playgroud)
您需要在标头中声明它:
extern Color someColor;
Run Code Online (Sandbox Code Playgroud)
并在.cpp文件中定义它:
Color someColor = {255, 255, 255};
Run Code Online (Sandbox Code Playgroud)
请注意,您的语法struct::Color极具误导性.它被解析为struct ::Color,并且在C++术语中,它等同于::Color或仅仅Color(除非你在命名空间内).