是否可以在 C++ 中声明一个变量而不实例化它?我想做这样的事情:
Animal a;
if( happyDay() )
a( "puppies" ); //constructor call
else
a( "toads" );
基本上,我只想在条件之外声明 a 以便获得正确的范围。
有没有办法做到这一点,而不使用指针并在堆上分配 a
?也许引用的一些聪明的东西?
最佳答案
你不能在这里使用引用,因为一旦你离开范围,引用就会指向一个将被删除的对象。
真的,你有两个选择:
1- 使用指针:
Animal* a;
if( happyDay() )
a = new Animal( "puppies" ); //constructor call
else
a = new Animal( "toads" );
// ...
delete a;
或使用智能指针
#include <memory>
std::unique_ptr<Animal> a;
if( happyDay() )
a = std::make_unique<Animal>( "puppies" );
else
a = std::make_unique<Animal>( "toads" );
2- 给Animal
添加一个Init方法:
class Animal
{
public:
Animal(){}
void Init( const std::string& type )
{
m_type = type;
}
private:
std:string m_type;
};
Animal a;
if( happyDay() )
a.Init( "puppies" );
else
a.Init( "toads" );
我个人会选择选项 2。
关于c++ - 在 C++ 中初始化对象之前声明一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/800368/