我如何初始化所有这些变量为零而不声明每个变量在一个新的行?

int column, row, index = 0;

当前回答

int column(0), row(0), index(0);

注意,这种形式也适用于自定义类型,特别是当它们的构造函数有多个参数时。

其他回答

int column = 0, row = 0, index = 0;
int column(0), row(0), index(0);

注意,这种形式也适用于自定义类型,特别是当它们的构造函数有多个参数时。

正如@Josh所说,正确答案是:

int column = 0,
    row = 0,
    index = 0;

对于指针,您需要注意同样的事情。这样的:

int* a, b, c;

等价于:

int *a;
int b;
int c;

从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

使用下面的声明,只有最后一个变量(index)被设置为0:

int column, row, index = 0;

相反,下面的代码将所有变量设置为0:

int column, row, index;
column = index = row = 0;

但就我个人而言,我觉得以下方法更有可读性:

int column = 0, row = 0, index = 0;
int column = 0;
int row = 0;
int index = 0;