【问题标题】:How to declare a reference variable to persist between conditional blocks?如何声明引用变量以在条件块之间持续存在?
【发布时间】: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 到? (编辑问题以使yi 的依赖性更清晰。)
  • @Milo:你必须使用引用吗?如果使用指针,只需将其初始化为 NULL,然后在使用 y 之前检查 not NULL
  • C 中没有引用。你的意思是 C++ 吗?

标签: c++ variables reference conditional


【解决方案1】:

这两种方法都适合你吗?

  1. 如果您没有使用引用的硬性要求,请尝试使用指针。然后您可以在父范围内声明它并使用 NULL 进行初始化。然后稍后在使用前检查 not-NULL。

  2. 如果 MyType 是一个对象,您可以让它从定义 IsInitialised() 的基础派生,然后调用它。如果 MyType 是一个标量,那么如果有一个值在该类型的范围内,但超出该类型所代表的范围,则使用这样的值来指示“未设置”并执行以下操作:

.

MyType notInitialised(NOT INITIALISED VALUE);
for (i = ...)
{
        MyType &x = expr_1(i) ? y[idx(i)] : notInitialised; 
        // code not needing x
        if (expr_2(i) && x != notInitialised) {
            ...
        }

希望有帮助吗?

【讨论】:

    猜你喜欢
    • 2021-05-14
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多