在c ++中初始化对象之前声明对象 [英] Declaring an object before initializing it in c++
问题描述
是否可以在c ++中声明一个变量而不实例化它?我想做这样的事情:
if(happyDay())
a(puppies); // constructor call
else
a(toads);
基本上,我只想声明一个外部的条件,所以它获得正确的范围。 p>
有没有办法做到这一点,不使用指针和在堆上分配 a
?
你不能直接在C ++中做到这一点,因为当你定义对象时默认构造函数。
但是,您可以运行一个参数化构造函数以开头:
Animal a(getAppropriateString());
或者你实际上可以使用 ?:运算符
确定正确的字符串。
(更新:@Greg给出了这个的语法,看到这个答案)
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" ); //constructor call
else
a( "toads" );
Basially, I just want to declare a outside of the conditional so it gets the right scope.
Is there any way to do this without using pointers and allocating a
on the heap? Maybe something clever with references?
You can't do this directly in C++ since the object is constructed when you define it with the default constructor.
You could, however, run a parameterized constructor to begin with:
Animal a(getAppropriateString());
Or you could actually use something like the ?: operator
to determine the correct string.
(Update: @Greg gave the syntax for this. See that answer)
这篇关于在c ++中初始化对象之前声明对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!