c++ - 在 C++ 中初始化对象之前声明一个对象

标签 c++ scope declaration instantiation

是否可以在 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/

相关文章:

clojure - 传递变量和元数据

c# - 如何在 C# 中使用 DLL 函数而不添加 DLL 作为引用?

java - List和ArrayList在声明上的区别?

c++ - QTextEdit 需要越来越多的时间来绘制文本

c++ - 在 SFML 中获取绝对顶点坐标?

c++ - 什么时候从函数的参数化中省略 const 是安全的?

javascript - 调用 jQuery-ui 插件中的函数有错误的上下文?

ruby - Ruby REPL 中的最后结果

c++ - 合并两个已排序的 vector

c - 方法返回的指针未正确分配给 C 中定义的另一个指针