如果我打算在多个条件块中使用它,我应该如何声明一个引用变量?例如:
for (i = ...) {
if (expr_1(i)) {
// y[idx(i)] only exists when expr_1 is true
// i.e. idx(i) is a valid index only when expr_1 is true
MyType &x = y[idx(i)];
...
}
... // Stuff not dependent on x
if (expr_2(i)) { // (expr_2 is such that expr_1 implies expr_2)
foo(x); // error, as x not scoped to persist to here
...
}
... // More stuff not dependent on x
if (expr_3(i)) { // (expr_3 is such that expr_1 implies expr_3)
bar(x); // error, as x not scoped to persist to here
...
}
... // etc
}
我不能在条件块之外声明它,因为引用变量必须在声明时初始化,但它引用的变量只存在于条件块中。