Calling constructors in c++ without new

前端 未结 7 1565
离开以前
离开以前 2020-12-04 05:20

I\'ve often seen that people create objects in C++ using

Thing myThing(\"asdf\");

Instead of this:

Thing myThing = Thing(\"         


        
7条回答
  •  一个人的身影
    2020-12-04 06:00

    I played a bit with it and the syntax seems to get quite strange when a constructor takes no arguments. Let me give an example:

    #include  
    
    using namespace std;
    
    class Thing
    {
    public:
        Thing();
    };
    
    Thing::Thing()
    {
        cout << "Hi" << endl;
    }
    
    int main()
    {
        //Thing myThing(); // Does not work
        Thing myThing; // Works
    
    }
    

    so just writing Thing myThing w/o brackets actually calls the constructor, while Thing myThing() makes the compiler thing you want to create a function pointer or something ??!!

提交回复
热议问题