General rules of passing/returning reference of array (not pointer) to/from a function?

后端 未结 6 1243
猫巷女王i
猫巷女王i 2020-12-02 06:58

We can pass reference of an array to a function like:

void f(int (&a)[5]);

int x[5];
f(x);     //okay
int y[6];
f(y);     //error - type of y is not `in         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 07:23

    If you want to return a reference to an array from a function, the declaration would look like this:

    // an array
    int global[10];
    
    // function returning a reference to an array
    int (&f())[10] {
       return global;
    }
    

    The declaration of a function returning a reference to an array looks the same as the declaration of a variable that is a reference to an array - only that the function name is followed by (), which may contain parameter declarations:

    int (&variable)[1][2];
    int (&functionA())[1][2];
    int (&functionB(int param))[1][2];
    

    Such declarations can be made much clearer by using a typedef:

    typedef int array_t[10];
    
    array_t& f() {
       return global;
    }
    

    If you want it to get really confusing, you can declare a function that takes a reference to an array and also returns such a reference:

    template
    int (&f(int (¶m)[M][N]))[M][N] {
       return param;
    }
    

    Pointers to arrays work the same, only that they use * instead of &.

提交回复
热议问题