C++ C++;在标头中定义并在cpp中实现的结构

C++ C++;在标头中定义并在cpp中实现的结构,c++,struct,implementation,C++,Struct,Implementation,在另一个类中使用somecolor时,如何确保我实现的somecolor保持其值 结构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 al

在另一个类中使用somecolor时,如何确保我实现的somecolor保持其值

结构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 Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};
extern Color someColor;
结构cpp

struct::Color someColor = {255,255,255};
struct *str = new struct();
str->someColor.r //is not the correct value /not set
#include "struct.h"    
Color someColor = {255,255,255};
#include "struct.h"
Color newColor;
newColor.r = someColor.r;
someotherclass.cpp

struct::Color someColor = {255,255,255};
struct *str = new struct();
str->someColor.r //is not the correct value /not set
#include "struct.h"    
Color someColor = {255,255,255};
#include "struct.h"
Color newColor;
newColor.r = someColor.r;
您需要在标题中声明它:

extern Color someColor;
并在.cpp文件中定义它:

Color someColor = {255, 255, 255};

请注意,您的语法
struct::Color
具有高度误导性。它被解析为<代码>结构::颜色< /代码>,在C++中,它等同于代码>::颜色< />代码>或只是<代码>颜色< /> >(除非你在命名空间内)。

我将把你的<代码>结构> <代码>改为<代码> MyStult< /Cord>,以便使它成为有效的C++。似乎您希望为
mystruct
提供一个默认构造函数,将其
someColor
成员初始化为
{255255255}
。在C++11之前,您必须这样做:

mystruct::mystruct()
{
  someColor.r = 255;
  someColor.g = 255;
  someColor.b = 255;
}
或者,如果给
Color
一个接受3个值的构造函数,则可以执行以下操作:

mystruct::mystruct()
  : someColor(255, 255, 255)
{ }
但是,在C++11中,您可以在成员初始化列表中进行聚合初始化,因此不需要为
mystruct
提供构造函数:

mystruct::mystruct()
  : someColor{255, 255, 255}
{ }
事实上,在C++11中,您可以初始化类定义中的非静态非常量成员,就像您尝试做的那样:

Color someColor = {255, 255, 255};

你应该这样写:

结构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 Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};
extern Color someColor;
结构cpp

struct::Color someColor = {255,255,255};
struct *str = new struct();
str->someColor.r //is not the correct value /not set
#include "struct.h"    
Color someColor = {255,255,255};
#include "struct.h"
Color newColor;
newColor.r = someColor.r;
someotherclass.cpp

struct::Color someColor = {255,255,255};
struct *str = new struct();
str->someColor.r //is not the correct value /not set
#include "struct.h"    
Color someColor = {255,255,255};
#include "struct.h"
Color newColor;
newColor.r = someColor.r;

请出示真实代码。不能有名为
struct
struct
。从最后一行判断,我认为我们遗漏了重要信息,即
someColor
是类的成员,而不是全局变量。要回答这个问题,我们需要知道(a)情况是否确实如此;以及(b)是否应该只有一个实例与类本身(静态成员)或与每个对象单独关联(非静态成员)。