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)
};
如何实现上述样式声明语义?
最佳答案
在 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
};
请注意使用自由存储的含义:分配在那里的对象不会在程序执行结束时被破坏(就像静态对象一样)或其他任何时候(没有相应的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;
}
关于c++ - 如何在 C++ 中声明一个带有填充信息的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889370/