分号上的函数参数

问题描述 投票:33回答:2
matrix_* matrix_insert_values(int n; double a[][n], int m, int n)
{
    matrix_* x = matrix_new(m, n);
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            x->v[i][j] = a[i][j];
    return x;
}

我的测试矩阵的例子

double in[][3] = {
    { 12, -51,   4},
    {  6, 167, -68},
    { -4,  24, -41},
    { -1, 1, 0},
    { 2, 0, 3},
};

我有点迷失,我无法弄清楚int n;在我的参数声明中是什么,它适用于C但C ++不允许这种实现。我想了解这是如何工作的,因为我要将此代码迁移到C ++。

c++ c matrix syntax
2个回答
41
投票

它很少使用 来自C99的功能 GNU扩展(GCC documentation),用于转发声明VLA声明符中使用的参数。

matrix_* matrix_insert_values(int n; double a[][n], int m, int n);

你看到int n怎么出现两次?第一个int n;只是实际int n的前向声明,最后是。它必须出现在double a[][n]之前,因为n用于a的声明。如果你可以重新排列参数,你可以把n放在a之前然后你不需要这个功能

matrix_* matrix_insert_values_rearranged(int m, int n, double a[][n]);

关于C ++兼容性的注意事项

需要明确的是,GNU扩展只是函数参数的前向声明。以下原型是标准C:

// standard C, but invalid C++
matrix_* matrix_insert_values_2(int m, int n, double a[][n]);

您无法从C ++调用此函数,因为此代码使用C ++不支持的可变长度数组。您必须重写该函数才能从C ++中调用它。


2
投票

如果这就是你总是从C调用它的方式(即在编译时固定n和m),那么在C ++中你可以这样做:

template <int N, int M>
void matrix_insert_values(const double (&a)[M][N]);

int main() {
  double in[5][3] = {
    { 12, -51,   4},
    {  6, 167, -68},
    { -4,  24, -41},
    { -1, 1, 0},
    { 2, 0, 3},
  };

  matrix_insert_values(in);
};

其中N和M作为模板参数,这些是在编译时从传递给函数的输入中自动推导出来的。

© www.soinside.com 2019 - 2024. All rights reserved.