gpt4 book ai didi

c++ - 如果 int 不是类,为什么 int x = int(5) 合法?

转载 作者:太空狗 更新时间:2023-10-29 23:30:01 30 4
gpt4 key购买 nike

据我所知,像这样在 C++ 中实例化一个整数是合法的:

int x = int(5);

作为一名 Java 程序员,我会假设这行代码调用传递“5”作为参数的整数的构造函数。我读到 int 不是一个类,因此没有构造函数。

那么,在那行代码中究竟发生了什么,以及以这种方式初始化 int 和以这种方式初始化之间的根本区别是什么:

int x = 5;

提前致谢!

最佳答案

I read though that int is not a class and thus has no constructor.

是的,技术上built-in types have no constructor .

what does exactly happen in that line of code

整数文字 5 被显式转换为 int(对于编译器来说主要是空操作)并分配给 x

what is the fundamental difference between initialising the int that way and int x = 5;

本质上没有区别。在大多数情况下,以下所有表达式都是相同的,除非您是语言律师(例如,最后一个表达式会阻止缩小,即如果值不能由类型表示则引发错误):

int x = 5;         // copy initialization
int y = int(5); // cast and copy initialization
int z = (int)5; // cast and copy initialization
int w(5); // direct initialization
int r{5}; // direct initialization

阅读more about initializations了解更详细的信息和差异。

关于c++ - 如果 int 不是类,为什么 int x = int(5) 合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34314143/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com