1

我需要填充结构的属性 x 和 y。鉴于我有很多成员 (x,y...) 并且每个人都具有相同的属性(读、写等),无论如何我可以用比这更短的方式做到这一点吗?

features.x.Read = GetAttribute(node,"x","Read",HexValue);
features.x.Write = GetAttribute(node,"x","Write",HexValue);
features.x.address = GetAttribute(node,"x","address",HexValue);
features.x.value = GetAttribute(node,"x","value",HexValue);

features.y.Read = GetAttribute(node,"y","Read",HexValue);
features.y.Write = GetAttribute(node,"y","Write",HexValue);
features.y.address = GetAttribute(node,"y","address",HexValue);
features.y.value = GetAttribute(node,"y","value",HexValue);

谢谢

4

3 回答 3

9

可能像这样

void set_members(Whatever& member, const char* name)
{
    member.Read = GetAttribute(node, name, "Read", HexValue);
    member.Write = GetAttribute(node, name, "Write", HexValue);
    member.address = GetAttribute(node, name, "address", HexValue);
    member.value = GetAttribute(node, name, "value", HexValue);
}

set_members(feature.x, "x");
set_members(feature.y, "y");

我不知道Whatever应该是什么,但你可以弄清楚。甚至可以使它成为模板类型。

于 2013-09-03T09:58:31.023 回答
6

好吧,虽然指令不少,但至少击键次数更少并且更易于阅读:

#define FILL(a, b) features.a.b = GetAttribute(node,#a,#b,HexValue)

FILL(x, Read);
FILL(x, Write);
FILL(x, address);
FILL(x, value);

FILL(y, Read);
FILL(y, Write);
FILL(y, address);
FILL(y, value);

#undef FILL
于 2013-09-03T09:54:34.587 回答
3

C 和 C++ 都有聚合初始化:显示 C 风格:http: //ideone.com/EXKtCo

struct X
{
   int some;
   const char* really_long;
   double and_annoying_variable_names;
};

int main()
{
    struct X x = { 42, "hello world", 3.14 };
    // reassign:
    struct X y = { 0, "dummy", 0.0 };
    x = y;


    return 0;
}
于 2013-09-03T10:03:23.517 回答