我不完全清楚你在最后一条评论中所说的"skip over an element in fbs[] such that it is not filled" 是什么意思,但我认为你可以通过保持所需元素数量的成员计数(比如int n;)来构建struct p,提供在fbs[4] 中填充的数组元素的数量。这样pts[4] 和fbs[4] 的大小都是固定的,但您只能在fbs[] 中使用n 元素
一个简短的例子将解释。以"some simple variables" 开头的struct f 开头,例如int a, b, c;,例如
#include <iostream>
#define NFBS 4
struct f
{
int a, b, c; /* some simple variables */
/* construct f */
f (int x = 0, int y = 0, int z = 0) : a(x), b(y), c(z) {}
/* overload of << to output variables */
friend std::ostream& operator<< (std::ostream& os, const f& fs) {
std::cout << " " << fs.a << " " << fs.b << " " << fs.c << '\n';
return os;
}
};
以上只是对a、b和c的直接初始化,每个结构中<<的重载只是提供了一种简单的输出方式和说明用法。
现在对于struct p,将fbs 的声明保持为固定大小fbs[NFBS],但添加一个成员变量int n;,用于保存fbs 中实际使用的元素数量,例如
struct p
{
int n; /* no. of elements (0 <= n < NFBS) */
struct f fbs[NFBS]; /* array of struct f */
p (int i = 0) : n(i) /* construct n struct f in fbs array */
{
if (n > NFBS) { /* validate n */
std::cerr << "error: struct p initial value out-of-range.\n";
/* handle error */
}
else {
for (int k = 0; k < n; k++)
fbs[k] = f(k+1, k+2, k+3); /* handle as desired */
}
}
/* overload of << to output variables */
friend std::ostream& operator<< (std::ostream& os, const p& ps) {
std::cout << "have fbs[" << ps.n << "]\n";
for (int i = 0; i < ps.n; i++)
std::cout << " fbs[" << i << "]: " << ps.fbs[i];
return os;
}
};
上面,构造函数初始化fbs 的n 元素。 (例如使用的虚拟值)。请求的元素数量根据NFBS 的最大值进行验证——如果它超出范围,您将需要处理该错误,但是您喜欢。
最后对于struct t,你添加相同的计数器成员int n来构造p(n)并初始化pts的每个元素,例如
struct t
{
int n; /* no. of elements for struct p fbs[n] */
struct p pts[NFBS]; /* array of struct p */
t (int i = 0) : n(i) /* constuct NFBS struct p, each initialized p(n) */
{
for (int k = 0; k < NFBS; k++)
pts[k] = p(n); /* handle as desired */
}
/* overload of << to output variables */
friend std::ostream& operator<< (std::ostream& os, const t& ts) {
std::cout << "\nhave pts[" << NFBS << "]\n";
for (int i = 0; i < NFBS; i++)
std::cout << "\npts[" << i << "]: " << ts.pts[i];
return os;
}
};
所以t 总是有pts[4] 每个初始化为struct p 有fbs 每个0-4 元素之间。对于struct p 具有2 然后在fbs 中使用4 元素的情况,一个简短的main() 实现上述内容将是:
int main () {
t foo{2}, bar{4};
std::cout << foo << bar;
}
使用/输出示例
$ ./bin/multi_struct_arr
have pts[4]
pts[0]: have fbs[2]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
pts[1]: have fbs[2]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
pts[2]: have fbs[2]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
pts[3]: have fbs[2]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
have pts[4]
pts[0]: have fbs[4]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
fbs[2]: 3 4 5
fbs[3]: 4 5 6
pts[1]: have fbs[4]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
fbs[2]: 3 4 5
fbs[3]: 4 5 6
pts[2]: have fbs[4]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
fbs[2]: 3 4 5
fbs[3]: 4 5 6
pts[3]: have fbs[4]
fbs[0]: 1 2 3
fbs[1]: 2 3 4
fbs[2]: 3 4 5
fbs[3]: 4 5 6
不知道您打算如何实现这组嵌套结构的更多信息,很难更精确,但这是我最初的想法,即如何在不同的情况下处理 fbs 中所需的不同数量的元素struct p.