C++ 中 int x=1 和 int x(1) 有什么区别?

发布于 2024-08-07 11:21:02 字数 372 浏览 3 评论 0原文

可能的重复:
C++ 中的复制之间是否有区别初始化和赋值初始化?

我是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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无需解释 2024-08-14 11:21:02

是的,对于内置类型 int x = 1;int x(1); 是相同的。

当构造类类型的对象时,两种不同的初始化语法略有不同。

Obj x(y);

这是直接初始化,并指示编译器搜索采用 y 的明确构造函数,或者 y 可以隐式转换为的内容,并且使用此构造函数来初始化 x。

Obj x = y;

这是复制初始化,指示编译器通过转换 y 并使用 Obj 的复制来创建临时 Obj构造函数来初始化x

y的类型与x的类型相同时,复制初始化相当于直接初始化

对于复制初始化,由于使用的临时值是隐式转换的结果,因此不考虑标记为显式的构造函数。构造类型的复制构造函数必须是可访问的,但复制本身可能会被编译器作为优化而消除。

Yes, for built in types int x = 1; and int x(1); are the same.

When constructing objects of class type then the two different initialization syntaxes are subtly different.

Obj x(y);

This is direct initialization and instructs the compiler to search for an unambiguous constructor that takes y, or something that y can be implicitly converted to, and uses this constructor to initialize x.

Obj x = y;

This is copy initialization and instructs the compiler to create a temporary Obj by converting y and uses Obj's copy constructor to initalize x.

Copy initalization is equivalent to direct initialization when the type of y is the same as the type of x.

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.

清欢 2024-08-14 11:21:02

对于 POD 类型,这两个语句是相同的。

For POD-types, both statements are identical.

夏末染殇 2024-08-14 11:21:02

我不是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文