VOID 函数通过引用传递数组,但在使用时,我会得到"No matching matching function for call to..."

VOID function passes array by reference, but when used, I get "No matching matching function for call to..."

本文关键字:matching No to call for function 引用 函数 数组 VOID      更新时间:2023-10-16

我写了下面的代码来用随机浮点数填充长度为len(已经初始化)的double数组:

void FillRay(double (&array)[] , const unsigned int len, const double a , const double b)
{
    for(unsigned int i = 0 ; i < len ; ++i )
    {
    array[i] = randFloat(a,b);   // Fill array at i with random number
    }
return;
}

然而,当我在main()中使用FillRay函数时(参见main的结尾)…

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <math.h>
using namespace std;
int main(){
    double a;
    double b;
    cout << "Please enter lower bound (a): ";
    cin >> a;
    cout << endl;
    cout << "Please enter upper bound (b): ";
    cin >> b;
    cout << endl;
    //Calculate mean and variance
    double mu = (b - a)/2;
    double sigma = pow(b - a , 2)/12;
    //Declare arrays (with langths)
    unsigned int shorter = 1000;
    unsigned int longer = 100000;
    double shortArray[shorter];
    double longArray[longer];
    // Fill array of length 1K
    FillRay(shortArray , shorter, a , b);    // ***THIS IS MY PROBLEM AREA***
    return 0;
}

…我得到错误没有匹配的函数调用'FillRay'

有人能解释一下我做错了什么吗?谢谢!

将函数原型修改为:

void FillRay(double* array, const unsigned int len, const double a , const double b)

此外,使用size_t而不是int表示数组大小也是一个很好的做法。

void FillRay(double (&array)[] , const unsigned int len, const double a , const double b)

double (&array)[]尝试在不指定数组大小的情况下通过引用获取数组。这是不可能的。您还指定了一个len参数,这在技术上是无关紧要的。如果你想使用没有任何专有扩展的标准c++,那么你有三个选择:

  1. 完全改变程序逻辑,使数组大小在编译时是固定的。
  2. 让函数取一个double*,并让从数组到指针的自动转换(非正式地称为"衰减")发生。
  3. 使用std::vector<double> .
相关文章: