声明参考并稍后初始化? [英] Declare a reference and initialize later?

查看:54
本文介绍了声明参考并稍后初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我引用了 MyOjbect ,但是确切的对象取决于条件。所以我想做这样的事情:

I have a reference to MyOjbect, but the the exact object depends on a condition. So I want to do something like this:

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

我现在无法执行此操作,因为编译器不允许我声明但不能初始化引用。我该怎么办才能达到我的目标?

I cannot do this right now because the compiler does not allow me to declare but not initialize a reference. What can I do to achieve my goal here?

推荐答案

您需要对其进行初始化。但是,如果您希望有条件地对其进行初始化,则可以执行以下操作:

You need to initliaze it. But if you would like to conditionally initialize it, you can do something like this:

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

这篇关于声明参考并稍后初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆