Declare a reference and initialize later?

后端 未结 10 2131
遥遥无期
遥遥无期 2020-12-01 05:58

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([co         


        
10条回答
  •  失恋的感觉
    2020-12-01 06:48

    AFAIK this can't be done with a reference. You'd have to use a pointer:

    MyClass *ptr;
    
    if (condition)
        ptr = &object;
    else
        ptr = &other_object;
    

    The pointer will act similar to a reference. Just don't forget to use -> for member access.

提交回复
热议问题