【发布时间】:2013-04-30 13:44:04
【问题描述】:
如果我打算在多个条件块中使用引用变量,我应该如何声明它?例如:
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
}
我不能在条件块之外声明它,因为引用变量必须在声明时初始化,但它引用的变量只存在于条件块中。
【问题讨论】:
-
您必须在父块中定义它,然后检查它是否已在每个块中初始化/准备。
-
好吧,
MyType byValVar; if (foo) { byValVar = y; } MyType &byRefVar = byValVar; -
感谢@MarcB,但是如果
y依赖于i并且在所有循环迭代的父块中不存在,我将要初始化什么x到? (编辑问题以使y对i的依赖性更清晰。) -
@Milo:你必须使用引用吗?如果使用指针,只需将其初始化为 NULL,然后在使用
y之前检查 not NULL -
C 中没有引用。你的意思是 C++ 吗?
标签: c++ variables reference conditional