如何声明一个引用并稍后初始化 [英] How to declare a reference and initialize later

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

问题描述

我是C ++的新手,这里是我的情况。我有一个引用 MyOjbect ,但确切的对象取决于一个条件。所以我想做这样的事情:

I am very new to C++ and here's my situation. 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?

推荐答案

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

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天全站免登陆