gpt4 book ai didi

c++ - 通过类构造函数了解何时在 () 和 {} 初始化中发生检查

转载 作者:行者123 更新时间:2023-12-04 15:10:08 24 4
gpt4 key购买 nike

据我所知,{} 是一种初始化变量的方法,与其他方法相比具有一些“安全”优势,例如禁止缩小:

int some_int_a = 1.2;  // narrows
int some_int_b (1.2); // narrows
int some_int_c {1.2}; // does NOT compile, cannot narrow

到目前为止一切顺利。我最近发现但我不完全理解的是,这种检查何时发生?例如,在下面的代码中:

#include <iostream>

class ExClass{
private:
const int i;
public:
ExClass(int i=0): i{i} {
// needed even if empty
}
void print(void){
std::cout << "const int i = " << i << std::endl;
}
};

int main(void)
{

ExClass ex_a (2.3); // narrows! this was surprising to me, I (probably naively)
// expected i{i} in the constructor to forbid this.
ex_a.print();

ExClass ex_b {2.3}; // does not compile
ex_b.print();

return 0;
}

我想这意味着在 ex_a 的情况下,首先完全使用收缩转换创建一个中间 int,然后这个中间 int 用于在构造函数中对 i 进行括号初始化。而在第二种情况下,中间 int 不能用有冲突的输入进行括号初始化,对吗?

有没有办法以没有“中间”缩小的方式编写内容,以便类括号初始化检测到错误输入?

最佳答案

这里发生的是构造函数:

ExClass(int i=0): i{i}

接受一个 int 参数,并在此处缩小:

ExClass ex_a (2.3);

很好。一旦进入构造函数,i 就是一个int(参数,而不是成员)。因此 i{i} 没有变窄(它是 intint)。你确实得到了the error当您将构造函数更改为:

ExClass(double i=0): i{i} { }

因为现在 i{i} 实际上变窄了。

注意 gcc 只发布 a warning使用默认设置并需要 -pedantic-errors 将其识别为错误。感谢 Remy 指出它实际上是错误,而不是警告。

关于c++ - 通过类构造函数了解何时在 () 和 {} 初始化中发生检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65360332/

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