extern "C" {
typedef struct Pair_s {
char *first;
char *second;
} Pair;
typedef struct PairOfPairs_s {
Pair *first;
Pair *second;
} PairOfPairs;
}
Pair pairs[] = {
{"foo", "bar"}, //this is fine
{"bar", "baz"}
};
PairOfPairs pops[] = {
{{"foo", "bar"}, {"bar", "baz"}}, //How can i create an equivalent of this NEATLY
{&pairs[0], &pairs[1]} //this is not considered neat (imagine trying to read a list of 30 of these)
};
Run Code Online (Sandbox Code Playgroud)
我怎样才能实现上面的样式声明语义?
在C++ 11中你可以写:
PairOfPairs pops[] = {
{ new Pair{"a", "A"}, new Pair{"b", "B"} },
{ new Pair{"c", "C"}, new Pair{"d", "D"} },
// the grouping braces are optional
};
Run Code Online (Sandbox Code Playgroud)
请注意使用免费存储的含义:在程序执行结束时(如静态对象)或其他任何时候(没有相应的delete),分配的对象不会被破坏.如果Pair是一个C结构并且不管理资源(并且你总是希望你的程序在它退出之前使用该内存),那么在托管实现中可能不是一个问题.
编辑:如果您不能使用C++ 11功能,您始终可以创建一个辅助函数.例:
static Pair* new_pair(const char* first, const char* second)
{
Pair* pair = new Pair;
pair->first = first;
pair->second = second;
return pair;
}
Run Code Online (Sandbox Code Playgroud)