Declaring an object before initializing it in c++

前端 未结 10 2194
你的背包
你的背包 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:45

    The best work around is to use pointer.

    Animal a*;
    if( happyDay() ) 
        a = new Animal( "puppies" ); //constructor call
    else
        a = new Animal( "toads" );
    
    0 讨论(0)
  • 2020-12-13 17:45

    You can also use std::move:

    class Ball {
    private:
            // This is initialized, but not as needed
            sf::Sprite ball;
    public:
            Ball() {
                    texture.loadFromFile("ball.png");
                    // This is a local object, not the same as the class member.
                    sf::Sprite ball2(texture);
                    // move it
                    this->ball=std::move(ball2);
            }
    ...
    
    0 讨论(0)
  • 2020-12-13 17:49

    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)

    0 讨论(0)
  • 2020-12-13 17:49

    You can't declare a variable without calling a constructor. However, in your example you could do the following:

    Animal a(happyDay() ? "puppies" : "toads");
    
    0 讨论(0)
提交回复
热议问题