【问题标题】:VOID function passes array by reference, but when used, I get "No matching matching function for call to..."VOID 函数通过引用传递数组,但在使用时,我得到“没有匹配的匹配函数调用...”
【发布时间】:2015-10-08 18:13:19
【问题描述】:

我编写了以下代码来用随机浮点数填充长度为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;
}

...我收到错误 No matching function for call to 'FillRay'

有人可以解释我做错了什么吗?谢谢!

【问题讨论】:

  • 可变长度数组不是标准的 C++,尽管您的编译器可能支持它作为扩展。使用后果自负。
  • 函数FillRay在哪里定义的?

标签: c++ arrays pass-by-reference void


【解决方案1】:

将您的函数原型更改为:

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

此外,使用 size_t 而不是 int 来表示数组大小也是一个好习惯。

【讨论】:

    【解决方案2】:
    void FillRay(double (&array)[] , const unsigned int len, const double a , const double b)
    

    double (&amp;array)[] 试图通过引用获取数组而不指定数组的大小。这是不可能的。您还指定 len 参数的事实在技术上是无关紧要的。如果您想使用没有任何专有扩展的标准 C++,那么您有三种选择:

    1. 完全更改程序逻辑,使数组大小在编译时固定。
    2. 让函数接受double* 并让从数组到指针的自动转换(非正式地称为“衰减”)发生。
    3. 使用std::vector&lt;double&gt;

    【讨论】:

      猜你喜欢
      • 2011-05-16
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-10
      相关资源
      最近更新 更多