C 中显式赋值和隐式赋值有什么区别?
int value = 5; // this type of assignment is called an explicit assignment
int value(5); // this type of assignment is called an implicit assignment
它们之间有什么区别(如果有的话)?显式赋值和隐式赋值在什么情况下有区别以及有何区别?
http://weblogs.asp.net/kennykerr/archive /2004/08/31/Explicit-Constructors.aspx
编辑:我实际上刚刚找到这篇文章,它使整个事情变得更加清晰......并且它提出了另一个问题,你应该(在一般)将采用原始类型(数字/布尔/字符串)的单个参数的构造函数标记为显式,并将其余部分保留原样(当然,请注意诸如 (int, SomeType 之类的构造函数)之类的陷阱= SomeType())
?
int value = 5; // this type of assignment is called an explicit assignment
int value(5); // this type of assignment is called an implicit assignment
What is the difference between those, if any, and in what cases do explicit and implicit assignment differ and how?
http://weblogs.asp.net/kennykerr/archive/2004/08/31/Explicit-Constructors.aspx
EDIT: I actually just found this article, which makes the whole thing a lot clearer... and it brings up another question, should you (in general) mark constructors taking a single parameter of a primitive type - numeric/bool/string - as explicit and leave the rest as they are (of course keeping watch for gotchas such as constructors like (int, SomeType = SomeType())
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这些都不是任何类型的赋值——它们都是初始化。第一个使用复制初始化,第二个使用直接初始化。 (FWIW,我很确定我以前从未听说过术语“显式赋值”或“隐式赋值”)。
编辑:(主要是为了回应内森的评论):
这是您评论中的代码的更正版本:
运行的结果应该是:
如果您运行它并得到
foo::assign()
,扔掉你的编译器并获得一个可以工作的编译器(哦,让我们知道它是什么编译器,它已经严重损坏了)!Neither of these is an assignment of any kind -- they're both initialization. The first uses copy initialization, and the second direct initialization. (FWIW, I'm pretty sure I've never heard the terms "explicit assignment" or "implicit assignment" before).
Edit: (Mostly in response to Nathan's comment):
Here's a corrected version of the code from your comment:
The result from running this should be:
If you run it and get an
foo::assign()
, throw your compiler away and get one that works (oh, and let us know what compiler it is that's so badly broken)!如果类具有标记为“显式”的构造函数,则它们会有所不同。那么,其中之一就不起作用了。
否则,没有区别。
They differ if a class has a constructor marked 'explicit'. Then, one of these does not work.
Otherwise, no difference.
只有第一个是作业。它们都是初始化。
编辑:实际上,我错了。任务也不是。
Only the first one is an assignment. They are both initialization.
Edit: actually, I'm wrong. Neither are assignment.