C++ empty String constructor

后端 未结 7 1912
误落风尘
误落风尘 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:17

    I don't think that in this case, the rule "if it could be a declaration, it's taken to be a declaration" applies. Since in the following, both things are declarations

    string a;
    string a();
    

    The one is the declaration of an object, and the other is the declaration of a function. The rule applies in other cases. For example, in this case:

    string a(string());
    

    In that case, string() can mean two things.

    • Declaration of an unnamed function parameter
    • Expression creating a default constructed string

    The fule applies here, and string() is taken to mean the same as the following, named parameter (names are irrelevant in parameters when declaring a function)

    string a(string im_not_relevant());
    

    If a function takes as parameter an array or another function, that parameter decays into a pointer. In case of a function parameter, to a pointer to the function. Thus, it is equivalent to the following, which may look more familiar

    string a(string (*im_not_relevant)());
    

    But in your case, it's rather the syntax that's getting into the way. It's saying that the following is a function declaration. It can never be the declaration of an object (even though that was probably intended by the programmer!)

    string a();
    

    So there is no ambiguity in this context in the first place, and thus it declares a function. Since string has a user defined constructor, you can just omit the parentheses, and the effect remains the same as what was intended.

提交回复
热议问题