C++中显式赋值和隐式赋值的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3057859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between explicit and implicit assignment in C++
提问by Jake Petroules
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
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())
?
编辑:我实际上刚刚找到了这篇文章,它使整个事情变得更加清晰......它带来了另一个问题,你(通常)是否应该标记采用原始类型的单个参数的构造函数 - numeric/bool/string -尽可能明确并保留其余部分(当然要注意诸如构造函数之类的陷阱(int, SomeType = SomeType())
?
采纳答案by Pavel Radzivilovsky
They differ if a class has a constructor marked 'explicit'. Then, one of these does not work.
如果类具有标记为“显式”的构造函数,则它们会有所不同。然后,其中之一不起作用。
Otherwise, no difference.
否则,没有区别。
回答by Jerry Coffin
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).
这些都不是任何类型的赋值——它们都是初始化。第一个使用复制初始化,第二个使用直接初始化。(FWIW,我很确定我以前从未听说过“显式分配”或“隐式分配”这两个术语)。
Edit: (Mostly in response to Nathan's comment):
编辑:(主要是为了回应内森的评论):
Here's a corrected version of the code from your comment:
这是您评论中代码的更正版本:
#include <iostream>
struct Foo {
Foo() {
std::cout << "Foo::ctor()" << std::endl;
}
Foo(Foo const& copy) {
std::cout << "Foo::cctor()" << std::endl;
}
Foo& operator=(Foo const& copy) {
std::cout << "foo::assign()" << std::endl;
return *this;
}
};
int main(int, const char**) {
Foo f;
Foo b(f);
Foo x = b;
return 0;
}
The result from running this should be:
运行它的结果应该是:
Foo::ctor()
Foo::cctor()
Foo::cctor()
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)!
如果你运行它并得到一个foo::assign()
,扔掉你的编译器并得到一个有效的(哦,让我们知道它是什么编译器,它被严重破坏了)!
回答by Edward Strange
Only the first one is an assignment. They are both initialization.
只有第一个是作业。它们都是初始化。
Edit: actually, I'm wrong. Neither are assignment.
编辑:实际上,我错了。也不是赋值。