为什么这段代码不起作用? (原型中的数组)

时间:2013-07-08 18:28:12

标签: c++ arrays function reference prototype

中午程序员好后,希望很高兴 这是代码:

    #include<iostream.h>


void sum(int &a[])
{
         a[2] = a[1] +a[0];
         }


int main()
{
    int a[3]={4,2,0};
    sum(a);
    cout<<a[2]<<endl;
}

我的编译器说:“声明'a'作为引用数组”              并且:“`a'未声明(首先使用此功能)” 我怎么能解决这个问题? 我有一个更大的代码但我想知道如何在函数中放入带引用的数组 我认为这是语法问题,我不知道在哪里找到解决方案,所以我来到这里 我在互联网上搜索了很多,但我不知道我如何搜索我的问题解决方案

原始代码:

  void Jump(int &y,int &y0, float V0 ,float &time, int &ground , int radius , int thickness_of_ground ,bool &protect_from_jump ,bool &ready_for_jump , bool (&key)[5])
  {
      int SPACE=4;
      float a_y=9.8;
      int FPS =60;

  if (protect_from_jump) key[SPACE]=false;

  if(!key[SPACE] && ground-(radius+thickness_of_ground)-y>0)
   {              
                  V0=0;
                  y=int(0.5*a_y*time*time -V0*time + y0);
                  time +=6.0/FPS;
                  protect_from_jump=true;
                  }
                  else if (!key[SPACE] &&  ground-(radius+thickness_of_ground)-y<=0)
                  {

                      y=ground -(radius+thickness_of_ground);
                      y0=y;
                      time=0;
                      protect_from_jump=false;

                  }

  if(key[SPACE])
  {
                if (ready_for_jump)
                {
                y0=y;
                ready_for_jump = false;
                }
              V0=40;  
              y=int(0.5*a_y*time*time -V0*time + y0);
              time +=6.0/FPS;

              if(ground-(radius+thickness_of_ground)+1-y<=0)
              {
              ready_for_jump=true;
              y=ground-(radius+thickness_of_ground);
              y0=y;
              time=0;
              key[SPACE]=false;
              }
                } 

}

1 个答案:

答案 0 :(得分:5)

真的尝试声明引用数组吗?如果是这样,那么你就是不能。

但是,如果要声明对数组的引用(在这种情况下我再也没有看到原因),那么必须将其括起来,因为[]的优先级高于& {1}}。此外,在这种情况下,您必须为数组提供维度,否则它是编译器错误:

void sum(int (&a)[10])
{
    // do stuff
}
相关问题