Declaring an object before initializing it in c++

前端 未结 10 2206
你的背包
你的背包 2020-12-13 17:17

Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:

Animal a;
if( happyDay() ) 
    a( \"puppies\" ); //c         


        
10条回答
  •  遥遥无期
    2020-12-13 17:28

    I prefer Greg's answer, but you could also do this:

    char *AnimalType;
    if( happyDay() ) 
        AnimalType = "puppies";
    else
        AnimalType = "toads";
    Animal a(AnimalType);
    

    I suggest this because I've worked places where the conditional operator was forbidden. (Sigh!) Also, this can be expanded beyond two alternatives very easily.

提交回复
热议问题