Returning multidimensional array from function

后端 未结 7 974
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:51

How do I return a multidimensional array stored in a private field of my class?

class Myclass {
private:
   int myarray[5][5];
public:
   int **         


        
7条回答
  •  没有蜡笔的小新
    2020-11-27 04:06

    There are two possible types that you can return to provide access to your internal array. The old C style would be returning int *[5], as the array will easily decay into a pointer to the first element, which is of type int[5].

    int (*foo())[5] {
       static int array[5][5] = {};
       return array;
    }
    

    Now, you can also return a proper reference to the internal array, the simplest syntax would be through a typedef:

    typedef int (&array5x5)[5][5];
    array5x5 foo() {
       static int array[5][5] = {};
       return array;
    }
    

    Or a little more cumbersome without the typedef:

    int (&foo())[5][5] {
       static int array[5][5] = {};
       return array;
    }
    

    The advantage of the C++ version is that the actual type is maintained, and that means that the actual size of the array is known at the callers side.

提交回复
热议问题