如何声明在条件块之间持久存在的引用变量
How to declare a reference variable to persist between conditional blocks?
如果我计划在多个条件块中使用引用变量,我应该如何声明它?例如:
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
}
我不能在条件块之外声明它,因为引用变量必须在声明时初始化,但是它引用的变量只存在于条件块中。
这两种方法都适合你吗?
-
如果您没有硬性要求使用引用,请尝试使用指针。然后你可以在父作用域中声明它并初始化为NULL。然后在使用前检查not-NULL
-
如果MyType是一个对象,你可以让它从定义了isinitialized()的基类派生,然后调用这个。如果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) {
...
}
希望有帮助?
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 为什么C++容器之间存在比较运算符
- 为什么返回前的值和返回后的值之间存在差异?
- 为什么堆栈中的函数局部变量之间存在内存空间
- 相对于一元算术运算符+,C和C++之间存在差异的原因是什么
- 函数返回类型和名称之间存在未知关键字
- 我找不到程序中的歧义,但编译器说 check(int) 和 check(float) 之间存在歧义
- 引用的初始化无效:指针和值之间存在差异
- VS2005调试模式和发布模式之间存在巨大的性能影响
- 为什么在Mac OS X上使用size_t时uint32_t和uint64_t之间存在歧义
- 如何提取两个括号之间存在的字符串
- 来自 vtable 的未定义符号是否意味着接口和实现之间存在错误
- 实时时间和用户时间之间存在巨大差异
- 在程序继续执行的同时,如何使代码的两部分之间存在时间间隔或延迟?C++
- g++输出和Visual Studio输出之间存在差异.浮点变量
- 为什么我的静态方法的返回值与定义的构造函数(在 c++ 中)之间存在类型不匹配?
- 复制构造函数和转发构造函数之间存在冲突
- libc++和libstdc++之间存在差异
- 指针上的interpret_cast在char和unsigned char之间存在缺陷
- 为什么在多重定义的情况下char*和char[]之间存在差异