c – 如何传递二维数组作为参数?

前端之家收集整理的这篇文章主要介绍了c – 如何传递二维数组作为参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的Matrx类被定义为
  1. class Matrx
  2. {
  3. double A[50][50];
  4. int m,n;
  5. public:
  6. Matrx(void);
  7. Matrx(int a,int b)
  8. {
  9. m=a;
  10. n=b;
  11. }
  12. Matrx operator +(Matrx b);
  13. Matrx Transpose(Matrx b);
  14. Matrx operator *(Matrx b);
  15. CString printMatrx();
  16. void readMatrx(double a[][]);
  17. Matrx TransposeMat(Matrx b);
  18. };
  19.  
  20. void Matrx::readMatrx(double a[][])
  21. {
  22. for(int i=0;i< m;i++)
  23. {
  24. for(int j=0;j< n;j++)
  25. A[i][j]=a[i][j];
  26. }
  27. }

智能感知给出如下所示的错误

1 IntelliSense: an array may not have elements of this type d:\bmadaptive_dd_v1.02\matrx.h 17 27 TestServer

为什么?

如何传递二维数组作为函数的参数?

解决方法

您需要正确地了解数组和指针.这包括“嗯!他们没有我以为是那么有用”的教训.在熟悉数组和指针的工作方式之后,您应该重新思考设计.

例如,在我看来,以下设计有很多优点:

  1. #ifndef MATRIX_HPP_INCLUDED
  2. #define MATRIX_HPP_INCLUDED
  3.  
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. class matrix
  8. {
  9. public:
  10. typedef std::vector<double>::size_type st;
  11. matrix() : rows_(0),cols_(0) {}
  12. matrix(int r,int c) : rows_(r),cols_(c),coeffs_(st(r)*c,0.0) {}
  13. void reset(int r,int c)
  14. { rows_=r; cols_=c; coeffs_.clear(); coeffs_.resize(st(r)*c,0.0); }
  15. int rows() const {return rows_;}
  16. int cols() const {return cols_;}
  17. double const& operator()(int i,int j) const {return coeffs_[indexof(i,j)];}
  18. double & operator()(int i,int j) {return coeffs_[indexof(i,j)];}
  19. double const* operator[](int i) const {return &coeffs_[indexof(i,0)];}
  20. double * operator[](int i) {return &coeffs_[indexof(i,0)];}
  21. void swap(matrix& that)
  22. {
  23. std::swap(this->rows_,that.rows_);
  24. std::swap(this->cols_,that.cols_);
  25. this->coeffs_.swap(that.coeffs_));
  26. }
  27. private:
  28. int rows_,cols_;
  29. std::vector<double> coeffs_;
  30. st indexof(int i,int j) const {return st(i)*cols+j;} // row major storage
  31. };
  32.  
  33. inline void swap(matrix& a,matrix& b) {a.swap(b);}
  34.  
  35. matrix& operator+=(matrix& lhs,matrix const& rhs);
  36. matrix operator+(matrix const& lhs,matrix const& rhs);
  37. matrix operator*(matrix const& lhs,matrix const& rhs);
  38. inline matrix& operator*=(matrix& lhs,matrix const& rhs)
  39. { matrix tmp = lhs * rhs; swap(tmp,lhs); return lhs; }
  40. ...
  41.  
  42. #endif

这样,您不会浪费任何小矩阵的空间,并且可以支持大型矩阵.另外,使用std :: vector而不是指向动态分配的内存的指针成员,就不需要定义你自己的拷贝构造函数,赋值运算符和析构函数.

当然,您可以使用boost :: multi_array作为矩阵替换,但是使用自定义矩阵类允许您在自己的命名空间中声明重载运算符,这是由于ADL(依赖于参数的查找)而需要的.

你可能会认为这不是真的回答你的问题.在这种情况下,让我强调,我认为你不完全了解数组和指针的工作/行为.这是你应该在一本体面的C书中查找的东西.人们可以写很多关于这个话题的页面.你不能指望看到一个简短的答案解释所有的怪癖.

查看Definite C++ Book Guide线程.

猜你在找的C&C++相关文章