C++ empty String constructor

后端 未结 7 1891
误落风尘
误落风尘 2021-02-13 02:56

I am a C++ beginner, so sorry if the question is too basic.

I have tried to collect the string constrcturs and try all them out (to remember them).

strin         


        
7条回答
  •  逝去的感伤
    2021-02-13 03:14

    This is a very popular gotcha. C++ grammar is ambiguous. One of the rules to resolve ambiguities is "if something looks like declaration it is a declaration". In this case instead of defining a variable you declared a function prototype.

    string strA();
    

    is equivalent to

    string strA(void);
    

    a prototype of a no-arg function which returns string.

    If you wish to explicitly call no-arg constructor try this:

    string strA=string();
    

    It isn't fully equivalent - it means 'create a temporary string using no-arg constructor and then copy it to initialize variable strA', but the compiler is allowed to optimize it and omit copying.

    EDIT: Here is an appropriate item in C++ FAQ Lite

提交回复
热议问题