我的Matrx类被定义为
class Matrx
{
double A[50][50];
int m,n;
public:
Matrx(void);
Matrx(int a,int b)
{
m=a;
n=b;
}
Matrx operator +(Matrx b);
Matrx Transpose(Matrx b);
Matrx operator *(Matrx b);
CString printMatrx();
void readMatrx(double a[][]);
Matrx TransposeMat(Matrx b);
};
void Matrx::readMatrx(double a[][])
{
for(int i=0;i< m;i++)
{
for(int j=0;j< n;j++)
A[i][j]=a[i][j];
}
}
智能感知给出如下所示的错误
1 IntelliSense: an array may not have elements of this type d:\bmadaptive_dd_v1.02\matrx.h 17 27 TestServer
为什么?
如何传递二维数组作为函数的参数?
解决方法
您需要正确地了解数组和指针.这包括“嗯!他们没有我以为是那么有用”的教训.在熟悉数组和指针的工作方式之后,您应该重新思考设计.
例如,在我看来,以下设计有很多优点:
#ifndef MATRIX_HPP_INCLUDED
#define MATRIX_HPP_INCLUDED
#include <vector>
#include <algorithm>
class matrix
{
public:
typedef std::vector<double>::size_type st;
matrix() : rows_(0),cols_(0) {}
matrix(int r,int c) : rows_(r),cols_(c),coeffs_(st(r)*c,0.0) {}
void reset(int r,int c)
{ rows_=r; cols_=c; coeffs_.clear(); coeffs_.resize(st(r)*c,0.0); }
int rows() const {return rows_;}
int cols() const {return cols_;}
double const& operator()(int i,int j) const {return coeffs_[indexof(i,j)];}
double & operator()(int i,int j) {return coeffs_[indexof(i,j)];}
double const* operator[](int i) const {return &coeffs_[indexof(i,0)];}
double * operator[](int i) {return &coeffs_[indexof(i,0)];}
void swap(matrix& that)
{
std::swap(this->rows_,that.rows_);
std::swap(this->cols_,that.cols_);
this->coeffs_.swap(that.coeffs_));
}
private:
int rows_,cols_;
std::vector<double> coeffs_;
st indexof(int i,int j) const {return st(i)*cols+j;} // row major storage
};
inline void swap(matrix& a,matrix& b) {a.swap(b);}
matrix& operator+=(matrix& lhs,matrix const& rhs);
matrix operator+(matrix const& lhs,matrix const& rhs);
matrix operator*(matrix const& lhs,matrix const& rhs);
inline matrix& operator*=(matrix& lhs,matrix const& rhs)
{ matrix tmp = lhs * rhs; swap(tmp,lhs); return lhs; }
...
#endif
这样,您不会浪费任何小矩阵的空间,并且可以支持大型矩阵.另外,使用std :: vector而不是指向动态分配的内存的指针成员,就不需要定义你自己的拷贝构造函数,赋值运算符和析构函数.
当然,您可以使用boost :: multi_array作为矩阵替换,但是使用自定义矩阵类允许您在自己的命名空间中声明重载运算符,这是由于ADL(依赖于参数的查找)而需要的.
你可能会认为这不是真的回答你的问题.在这种情况下,让我强调,我认为你不完全了解数组和指针的工作/行为.这是你应该在一本体面的C书中查找的东西.人们可以写很多关于这个话题的页面.你不能指望看到一个简短的答案解释所有的怪癖.
查看Definite C++ Book Guide线程.