C++ default constructor: string params vs string params() [duplicate]

三世轮回 提交于 2019-12-11 00:59:30

问题


Possible Duplicate:
Is no parentheses on a constructor with no arguments a language standard?

Can anyone explain why these line don't give me an error:

string params;
params+="d";

but these lines:

string params();
params+="d";

give me this error: error C2659: '+=' : function as left operand


回答1:


This is not object:

 string params();

This is function returning string:

 string params();

Like this:

 string params(void);

So the error now is obvious: function as left operand

This problem has own name: http://en.wikipedia.org/wiki/Most_vexing_parse




回答2:


In the first case with the

string params;

creates a string instance using a default constructor.

In the second case the

string params();

creates a pointer to a function returning string. On that type the operator+=(const string&) is apparently not defined.

Yes, it is a bit confusing feature of the language because when you use not default constructor, you could really write e.g.

string params("d");


来源:https://stackoverflow.com/questions/12911078/c-default-constructor-string-params-vs-string-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!