我引用了某个类 MyObject
,但确切的对象取决于条件。我想做这样的事情:
MyObject& ref;
if([condition])
ref = MyObject([something]);
else
ref = MyObject([something else]);
我现在不能这样做,因为编译器不允许我声明但不能初始化引用。我能做些什么来实现我的目标?
原文由 user1861088 发布,翻译遵循 CC BY-SA 4.0 许可协议
我引用了某个类 MyObject
,但确切的对象取决于条件。我想做这样的事情:
MyObject& ref;
if([condition])
ref = MyObject([something]);
else
ref = MyObject([something else]);
我现在不能这样做,因为编译器不允许我声明但不能初始化引用。我能做些什么来实现我的目标?
原文由 user1861088 发布,翻译遵循 CC BY-SA 4.0 许可协议
我有一个类似的问题,我以一种不太聪明的方式解决了它。问题:我需要声明一个变量,它的类型由“数据”元素决定;该变量将在第一个 if 条件之外使用,因此需要在第一个 if 条件之外对其进行初始化。
错误代码:
Ivar& ref; // invalid, need init
if([condition]){
ref = data["info"];
if (ref.is_dict()) {
...
}
}
string x = ref["aa"];
在条件中使用临时变量
Ivar& ref = dict(); // Ivar and dict are faked; Ivar is interface variable
if([condition]){
Ivar& ref_tmp = data["info"];
if (ref_tmp.is_dict()) { // if the type of temp variable is correct
ref = ref_tmp // assign ref_tmp to ref
...
}
}
string x = ref["aa"];
原文由 JOE yue 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
1 回答1.6k 阅读✓ 已解决
你需要初始化它。但是如果你想有条件地初始化它,你可以这样做: