直接初始化与基元的复制初始化(Direct Initialization vs Copy Initialization for Primitives)

编程入门 行业动态 更新时间:2024-10-23 20:23:30
直接初始化与基元的复制初始化(Direct Initialization vs Copy Initialization for Primitives)

初始化基本类型(如int或指针)时,可以使用复制初始化直接初始化

int a = 10; int b(10);

虽然后一种方式是为具有构造函数的对象提供的,但我没有看到人们将它用于基元。 我理解使用'='运算符是“更自然”(特别是数字),但有人在现实代码中编写代码:

for (int i(0); i < 5; ++i) { cout << i << endl; }

谢谢。

编辑:问题是关于编码风格和最佳实践而不是技术实现。

When initializing primitive types like int or pointers one can use either copy-initialization or direct-initialization.

int a = 10; int b(10);

Although the latter way is preffered for objects with constructors, I don't see people using it for primitives. I understand that it is kind of "more natural" (especially for numbers) to use the '=' operator but is there anybody writing things like in real-life code:

for (int i(0); i < 5; ++i) { cout << i << endl; }

Thanks.

EDIT: The question asks about coding styles and best practices rather than technical implementation.

最满意答案

有些人这样做是为了保持一致。

在模板内部,代码可以是

for (T i(0); i < 5; ++i) { cout << i << endl; }

并且以任何方式编写它将使编码风格保持一致。

Some people do this to be consistent.

Inside a template, the code could be

for (T i(0); i < 5; ++i) { cout << i << endl; }

and writing it that way everywhere would make the coding style consistent.

更多推荐

本文发布于:2023-07-23 18:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   化与   Direct   Primitives   Copy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!