gpt4 book ai didi

c++ - 当在 C++11 中使用带有两个声明的 auto 时会发生什么?

转载 作者:行者123 更新时间:2023-11-30 01:46:42 24 4
gpt4 key购买 nike

假设有这样一个循环:

for(size_t i=0, n=ar.size(); i<n; ++i)
{
// ...
}

重写为:

for(auto i=0, n=ar.size(); i<n; ++i)
{
// ...
}

换句话说,in 这两个变量总是以相同的数据类型结束。

当我尝试这样的事情时:

auto i=0, s="";

g++ 4.8.4 生成错误 inconsistent deduction for ‘auto’: ‘int’ and then ‘const char*’。但我无法确定它是否只是 g++,或者根据标准实际上需要在类型推导中使用每个值。

最佳答案

这是 [dcl.spec.auto, 7.1.6.4]/8:

If the init-declarator-list contains more than one init-declarator, they shall all form declarations of variables. The type of each declared variable is determined as described above, and if the type that replaces the placeholder type is not the same in each deduction, the program is ill-formed.

也就是说,所有推导的类型必须相同。

同段中甚至还有一个例子:

auto x = 5, *y = &x;       // OK: auto is int
auto a = 5, b = { 1, 2 }; // error: different types for auto

关于c++ - 当在 C++11 中使用带有两个声明的 auto 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778604/

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