好了,我知道如何從函數返回二維數組:C++返回常量二維數組
struct S
{
int a[3];
int b[4][5];
int const *getA() const {return a;}
int (*getB())[5] {return b;}
};
的問題是:我怎麼回不斷二維數組?我應該在哪裏放置const
在線
int (*getB())[5] {return b;}
?
好了,我知道如何從函數返回二維數組:C++返回常量二維數組
struct S
{
int a[3];
int b[4][5];
int const *getA() const {return a;}
int (*getB())[5] {return b;}
};
的問題是:我怎麼回不斷二維數組?我應該在哪裏放置const
在線
int (*getB())[5] {return b;}
?
使用std::array
代替:
struct S
{
using arrayA_type = std::array<int, 3>;
using arrayB_type = std::array<std::array<int, 5>, 4>;
arrayA_type a;
arrayB_type b;
const arrayA_type& getA() const { return a; }
const arrayB_type& getB() const { return b; }
};
當然你也可以使用普通的原料數組,但它會多容易,如果你使用一個類型別名它,換句話說沒有混淆在哪裏把const
。
使用std::array
(或std::tr1::array
或boost::array
如果您沒有C++ 11支持)簡化整個事情。這些類型是可複製的,可分配的,並且它們的參考語法是明確的:
#include <array>
struct S
{
std::array<int, 3> a;
std::array<std::array<int, 5>, 4> b;
const std::array<int, 3>& getA() const {return a; }
const std::array<std::array<int, 5>, 4>& getB() const { return b; }
};
爲了您的理智,請使用'std :: array'這樣的東西。 – Pubby 2013-04-11 10:49:27
*「我知道如何從函數返回2d數組」* - 不,你不知道,因爲這是不可能的。你知道的是如何從函數返回一個指向數組的指針。 – 2013-04-11 11:06:55