C++ 中 int x=1 和 int x(1) 有什么区别?
我是C++新手,我很少看到有人使用这种语法来声明和初始化变量:
int x(1);
我尝试过,编译器没有抱怨并且输出与int x=1相同,是他们实际上是同一件事吗?
非常感谢大家。
Possible Duplicate:
Is there a difference in C++ between copy initialization and assignment initialization?
I am new to C++, I seldom see people using this syntax to declare and initialize a variable:
int x(1);
I tried, the compiler did not complain and the output is the same as int x=1, are they actually the same thing?
Many thanks to you all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,对于内置类型
int x = 1;
和int x(1);
是相同的。当构造类类型的对象时,两种不同的初始化语法略有不同。
这是直接初始化,并指示编译器搜索采用
y
的明确构造函数,或者y
可以隐式转换为的内容,并且使用此构造函数来初始化 x。这是复制初始化,指示编译器通过转换
y
并使用Obj
的复制来创建临时Obj
构造函数来初始化x
。当
y
的类型与x
的类型相同时,复制初始化相当于直接初始化。对于复制初始化,由于使用的临时值是隐式转换的结果,因此不考虑标记为
显式
的构造函数。构造类型的复制构造函数必须是可访问的,但复制本身可能会被编译器作为优化而消除。Yes, for built in types
int x = 1;
andint x(1);
are the same.When constructing objects of class type then the two different initialization syntaxes are subtly different.
This is direct initialization and instructs the compiler to search for an unambiguous constructor that takes
y
, or something thaty
can be implicitly converted to, and uses this constructor to initialize x.This is copy initialization and instructs the compiler to create a temporary
Obj
by convertingy
and usesObj
's copy constructor to initalizex
.Copy initalization is equivalent to direct initialization when the type of
y
is the same as the type ofx
.For copy initalization, because the temporary used is the result of an implicit conversion, constructors marked
explicit
are not considered. The copy constructor for the constructed type must be accessible but the copy itself may be eliminated by the compiler as an optmization.对于 POD 类型,这两个语句是相同的。
For POD-types, both statements are identical.
我不是 C++ 专家,但如果它给出相同的结果,这有关系吗?我想如果您真的感兴趣,您可以编译(但不是汇编)您的代码并看看有什么区别。
编辑:正如其他地方提到的,它们对于内置类型确实是相同的。
I'm no C++ expert, but if it gives the same result, does it matter? I guess if you were REALLY interested, you could compile (but not assemble) your code and have a look at what the difference is.
Edit: As has been mentioned elsewhere, they really are the same for builtin types.