C++11 Difference in Constructors (Braces)

前端 未结 2 2021
忘了有多久
忘了有多久 2021-01-19 19:02

I am quite new to C++ and have observed, that the following lines of code act differently

MyClass c1;
c1.do_work() //works
MyClass c2();
c2.do_work() //compi         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-19 19:45

    The second version

    MyClass c2();
    

    is a function declaration - see the most vexing parse and gotw.

    The first case is default initialisation.

    The last case, new to C++11, will call the default constructor, if there is one, since even though it looks like an initialiser list {}, it's empty.

提交回复
热议问题