简体   繁体   中英

How to return two-dimensional arrays in C++

I am trying to implement a Matrix4x4 class for my port of 3D Engine that I had made earlier. Here is what I have so far in my header file:

#ifndef MAT4_H
#define MAT4_H

class Matrix4
{

public:
   Matrix4() {}
   float[4][4] getMatrix() { return m; }
   //...
   //other matrix related methods are omitted
   //...
private:
   float m[4][4]; 

};

#endif

But the method that is supposed to return the two-dimensional array causes this error:

src/Matrix4.h:13:10: error: expected unqualified-id before '[' token
    float[4][4] getMatrix() { return m; }
         ^

I am sorry if this question already has an answer, but the answers that I found on this site were usually about returning pointers instead of an array. Hope you can help, thanks.

I would suggest to use std::array . But using it directly in code, as multi array, is a bit ugly. So I'd suggest an alias, defined as:

#include <array> 

namespace details 
{    
   template<typename T, std::size_t D, std::size_t ... Ds> 
   struct make_multi_array 
    : make_multi_array<typename make_multi_array<T,Ds...>::type, D> {}; 

   template<typename T, std::size_t D>
   struct make_multi_array<T,D> { using type = std::array<T, D>;  };
}

template<typename T, std::size_t D, std::size_t  ... Ds> 
using multi_array = typename details::make_multi_array<T,D,Ds...>::type;

Then use it as:

public:

   multi_array<float,4,4> getMatrix() { return m; }

private:
   multi_array<float,4,4> m;

You could use the alias in other places as well, such as:

 //same as std::array<int,10> 
 //similar to int x[10] 
 multi_array<int,10>   x;   

 //same as std::array<std::array<int,20>,10>
 //similar to int y[10][20] 
 multi_array<int,10,20> y;   

 //same as std::array<std::array<std::array<int,30>,20>,10>
 //similar to int z[10][20][30]
 multi_array<int,10,20,30> z; 

Hope that helps.

Passing an array in either C or C++ is possible by a passing pointer to its first element- the pointer is passed by value.

The only way to pass your array by value would be to encapsulate it in a struct, but in most cases its better to pass a pointer then to copy all the data by value.

Just return a pointer to the first element of the array! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM