我如何初始化所有这些变量为零而不声明每个变量在一个新的行?
int column, row, index = 0;
我如何初始化所有这些变量为零而不声明每个变量在一个新的行?
int column, row, index = 0;
当前回答
如果每行声明一个变量/对象,不仅可以解决这个问题,还可以使代码更清晰,并防止在声明指针时犯愚蠢的错误。
为了直接回答您的问题,您必须显式地将每个变量初始化为0。Int a = 0, b = 0, c = 0;
其他回答
int column = 0, row = 0, index = 0;
正如其他人所提到的,从c++ 17开始,你可以使用结构化绑定来进行多个变量的赋值。
结合std::array和模板参数推导,我们可以编写一个函数,将值赋给任意数量的变量,而无需重复类型或值。
#include <iostream>
#include <array>
template <int N, typename T> auto assign(T value)
{
std::array<T, N> out;
out.fill(value);
return out;
}
int main()
{
auto [a, b, c] = assign<3>(1);
for (const auto& v : {a, b, c})
{
std::cout << v << std::endl;
}
return 0;
}
Demo
int column(0), row(0), index(0);
注意,这种形式也适用于自定义类型,特别是当它们的构造函数有多个参数时。
从c++ 17开始,你可以使用结构化绑定:
#include <iostream>
#include <tuple>
int main ()
{
auto [hello, world] = std::make_tuple("Hello ", "world!");
std::cout << hello << world << std::endl;
return 0;
}
Demo
正如@Josh所说,正确答案是:
int column = 0,
row = 0,
index = 0;
对于指针,您需要注意同样的事情。这样的:
int* a, b, c;
等价于:
int *a;
int b;
int c;