【问题标题】:How to declare a function which takes an array by reference as an argument in C++?如何在 C++ 中声明一个通过引用将数组作为参数的函数?
【发布时间】:2021-09-18 21:40:47
【问题描述】:

我有这个带有函数的代码,它通过引用获取二维数组,并通过模板将其边界作为参数:

#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] = '.';
        }
    }
}

我需要在主代码块之前声明这个函数,然后在它之后定义。如何正确执行此操作?

【问题讨论】:

  • 为什么不避免问题,把定义放在首位?

标签: c++ function arguments


【解决方案1】:

只要把声明放在你想要的地方:

#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] = '.';
        }
    }
}

Godbolt example

【讨论】:

    【解决方案2】:

    只需删除函数体:

    template <size_t rows, size_t cols>
    void Foo(char (&array)[rows][cols]);
    

    【讨论】:

    • "只需删除函数体" 可能被误解为您建议从当前定义中删除函数体,而您的意思是 OP 应该复制定义到程序的顶部,然后从该副本中删除函数体,只留下声明(我假设)。
    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多