我目前正在移植一些我写给C ++的C代码以供娱乐。我有挣扎malloc()呼叫我在做C,与h和w是为简单起见常数,但后来随着运行时间的常数交换:
double (*g2)[h][w] = malloc(h * w * sizeof(double));
Run Code Online (Sandbox Code Playgroud)
在C语言中,这是A的隐式转换void*,而C ++当然不会实现。
我已经尝试使用进行强制转换reinterpret_cast<double[h][w]>,但这仍然是无效的强制转换。
我想知道如何才能用C ++进行这项工作,因为这可以节省很多工作?
作为替代,我可能会使用带间接的矩阵类:
struct Matrix : std::vector<double> {
unsigned matSize;
std::vector<double*> indirection;
Matrix() : matSize(0) {}
Matrix(unsigned n) : matSize(n) {
resize(n*n);
indirection.resize(n);
for(unsigned i = 0; i < n; ++i) {
indirection[i] = &(*this)[i*n];
}
}
double& operator()(unsigned i, unsigned j) {
return indirection[i][j];
}
const double& operator()(unsigned i, unsigned j) const {
return indirection[i][j];
} …Run Code Online (Sandbox Code Playgroud)