【发布时间】:2014-07-12 23:33:00
【问题描述】:
如何在类中设置指向外部静态数据结构的指针?
struct Str {
double **matr; // which type should matr be?
int nx, ny;
template<size_t rows, size_t cols>
void Init(double(&m)[rows][cols], int sx, int sy) {
matr = m; // <-- error
nx = sx; ny = sy;
}
};
...
static double M[3][5] = { { 0.0, 1.0, 2.0, 3.0, 4.0 },
{ 0.1, 1.1, 2.1, 3.1, 4.1 },
{ 0.2, 1.2, 2.2, 3.2, 4.2 } };
Str s;
s.Init(M, 3, 5);
使用此代码,我收到以下编译时错误消息 (Visual C++ 2008/2012):
1> 错误 C2440:“=”:无法从“double [3][5]”转换为“double **”
1> 指向的类型不相关;转换需要 reinterpret_cast、C 样式转换或函数样式转换
1> 参见正在编译的函数模板实例化 'void S::Init4(double (&)[3][5],int,int)' 的参考
【问题讨论】:
-
你对
M的过度使用可能会让人感到困惑——你有Mdoubles的静态数组和Mvoid Str::Init()函数的模板参数。您打算double (*m)[M]参考哪一个?我想你希望你的mattr只是double *mattr,或者更丑的double (*mattr)[5]... -
@twalberg - 谢谢,我修好了。
-
double(*m)[S] 是什么意思?是函数指针数组吗?
-
@Cool_Coder - 这是一个二维数组。现在应该更清楚了。
-
好的,有什么问题吗?没有编译吗?