声明一个引用并稍后初始化?

新手上路,请多包涵

我引用了某个类 MyObject ,但确切的对象取决于条件。我想做这样的事情:

 MyObject& ref;
if([condition])
  ref = MyObject([something]);
else
  ref = MyObject([something else]);

我现在不能这样做,因为编译器不允许我声明但不能初始化引用。我能做些什么来实现我的目标?

原文由 user1861088 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 843
2 个回答

你需要初始化它。但是如果你想有条件地初始化它,你可以这样做:

 MyObject& ref = (condition) ? MyObject([something]) : MyObject([something else]);

原文由 Zaffy 发布,翻译遵循 CC BY-SA 3.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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题