如何在 C++ 中声明一个通过引用将数组作为参数的函数?
How to declare a function which takes an array by reference as an argument in C++?
我有这段代码,其函数通过引用获取二维数组并将其边界作为参数:
#include <stdio.h>
void Foo(); // I need it here
int main()
{
char Space[10][10];
Foo(Space);
return 0;
}
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols])
{
size_t j;
size_t i;
for (j = 0; j < rows; j++)
{
for (i = 0; i < cols; i++)
{
array[i][j] = '.';
}
}
}
我需要在主代码块之前声明这个函数,然后在它之后定义。如何正确执行此操作?
只需删除函数体:
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols]);
只需将该声明放在您想要的位置即可:
#include <stdio.h>
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols]);
int main()
{
char Space[10][10];
Foo(Space);
return 0;
}
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols])
{
size_t j;
size_t i;
for (j = 0; j < rows; j++)
{
for (i = 0; i < cols; i++)
{
array[i][j] = '.';
}
}
}
我有这段代码,其函数通过引用获取二维数组并将其边界作为参数:
#include <stdio.h>
void Foo(); // I need it here
int main()
{
char Space[10][10];
Foo(Space);
return 0;
}
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols])
{
size_t j;
size_t i;
for (j = 0; j < rows; j++)
{
for (i = 0; i < cols; i++)
{
array[i][j] = '.';
}
}
}
我需要在主代码块之前声明这个函数,然后在它之后定义。如何正确执行此操作?
只需删除函数体:
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols]);
只需将该声明放在您想要的位置即可:
#include <stdio.h>
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols]);
int main()
{
char Space[10][10];
Foo(Space);
return 0;
}
template <size_t rows, size_t cols>
void Foo(char (&array)[rows][cols])
{
size_t j;
size_t i;
for (j = 0; j < rows; j++)
{
for (i = 0; i < cols; i++)
{
array[i][j] = '.';
}
}
}