2012-03-21 143 views
0

我正在写一个矩阵类,我希望能够将固定大小的矩阵转换为固定大小的双数组。虽然,我有麻烦执行适当的演员操作。我到目前为止已经实现不起作用:C++:将对象投射到数组

template<unsigned int M, unsigned int N> 
class Matrix 
{ 
    typedef double (&ArrayType)[M][N]; 
public: 
    operator ArrayType(); 
} 


Matrix<3,3> mat1; 
double matArr[3][3]; 
matArr = mat1; 

error: incompatible types in assignment of ‘sfz::Matrix<3u, 3u>’ to ‘double [3][3]’

铸造矩阵明确导致另一个错误:

error: ISO C++ forbids casting to an array type ‘double [3][3]’

有没有办法来实现我想要实现的语法?

回答

6

无法分配数组。和它一起生活。

为了使您的工作的功能,你可以做一个参考

double (&ar)[3][3] = mat1; 

或者,你可以包裹的东西你的裸体像数组和std::array<std::array<double, M>, N>按值返回。这就是为什么像std::array这样的包装存在–它们允许你将数组视为值。从第一天开始(把一个结构内的阵列)相同的技巧用C工作,但它实际上是很好的和可读的在C++:

typedef typename std::array<std::array<T, M>, N> type; 
operator type() const { return internal_array; } 
+0

请告诉我双(AR)之间的差[3] [3]和双AR [3] [3]? – Paranaix 2012-03-21 07:49:30

+0

@Paranaix:第一个是参考,第二个不是。 – 2012-03-21 07:50:39