gpt4 book ai didi

c++ - 在 C++ 中用 double 初始化 int 之间的区别

转载 作者:太空狗 更新时间:2023-10-29 20:02:11 26 4
gpt4 key购买 nike

在c++中这种初始化有什么区别;

int a = 0;
int a{};
int ();

为什么这个代码 int a{3.14} 让我出错但是这个 int a = 3.14 或者这个 int a(3.14)不要

最佳答案

这叫做列表初始化(C++11):

int foo = 0; // Initialize foo with 0
int foo{}; // Initialize foo with foo's type (int) default value, which is 0
int foo(); // Function declaration

int bar = 5.f; // Initialize bar with 5 (narrowing conversion from floating point)
int bar{5.f}; // Doesn't compile, because there is a loss of data when casting a float to an int
int bar(5.f); // Initialize bar with 5 (narrowing conversion from floating point)

但是:

float f{5}; // Okay, because there is no loss of data when casting an int to a float

关于c++ - 在 C++ 中用 double 初始化 int 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45104807/

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