1

我想制作多个结构,具有不同的设置......!它们都持有相同的变量(相同的名称等)!但是不同的实现!而且这个设置应该可以从另一个班级访问......这是最好的方法吗?还是我做错了什么?

啊:

class A
{
};

struct Color{
   unsigned char r;
   unsigned char g;
   unsigned char b;
};

extern struct Settings settings;

A.cpp

struct settings{
   Color firstcolor = {0,0,0}; //error: data member initializer is not allowed
   Color secondcolor = {255,255,255}; //error: data member initializer is not allowed
};
struct anothersettings{
   Color firstcolor = {255,255,255}; //error: data member initializer is not allowed
   Color secondcolor = {0,0,0}; //error: data member initializer is not allowed
};

B.cpp

#include "A.h"
dosomethingwith(settings);
4

1 回答 1

3

似乎您在struct类型和该类型的对象之间感到困惑。a 的全部意义struct在于它描述了该类型对象的外观。如果您要创建两个struct具有完全相同成员的 s(就像您使用settingsand所做的那样anothersettings),您可能会犯一个大错误。相反,您应该拥有一个struct然后是多个该类型的对象。

你最好有一个struct Settings像这样的单曲:

struct Settings {
  Color firstcolor;
  Color secondcolor;
};

然后您可以创建这种类型的对象,并根据需要设置颜色:

Settings settings1;
settings1.firstcolor.r = 0;
settings1.firstcolor.g = 0;
// And so on...

Settings settings2;
settings2.firstcolor.r = 255;
settings2.firstcolor.g = 255;
// And so on...

事实上,使用聚合初始化有一个更好的方法来编写它:

Settings settings1 = {{0, 0, 0}, {255, 255, 255}};
Settings settings2 = {{255, 255, 255}, {0, 0, 0}};

然后你可以有一个带Settings参数的函数:

void soSomething(Settings);

然后你可以这样调用:

doSomething(settings1);
// or
doSomething(settings2);
于 2013-04-08T14:28:30.533 回答