help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

what is wrong with this destruction function?


From: jack
Subject: what is wrong with this destruction function?
Date: 26 Feb 2005 08:24:14 -0800
User-agent: G2/0.2

when I run this code,the destruction function always run two time!
who know where is wrong?
thanks
#include <iostream.h>
#include <fstream.h>
#include <vector.h>
template<typename Elemtype>
class Matrix{
public:
  Matrix(int row,int column);
  Matrix(Matrix &);
  ~Matrix();
  void  resetelem(int i,int j,Elemtype Rvalue){
    _matrix[i*_row+j]=Rvalue;
  }
  int row(){return _row;}
  int column(){return _column;}
  Elemtype operator()(int i,int j) const
  {return _matrix[i*_row+j];
  }
  /*
  Elemtype& operator()(int i,int j)
  {return _matrix[i*row+j];
  }
  */
  ostream& print(ostream &os);
private:
  int _row;
  int _column;
protected:
  Elemtype *_matrix;
};
template <typename Elemtype>
Matrix<Elemtype>::Matrix(int row,int column){
  _row=row;
  _column=column;
  _matrix=new Elemtype[row*column];
  for(int i=0;i<column*row;i++){
  _matrix[i]=0;
  }
}

template <typename Elemtype>
Matrix<Elemtype>::~Matrix(){
  delete [] _matrix;
}



template <typename Elemtype>
ostream& Matrix<Elemtype>::print(ostream &os){
    for(int i=0;i<_row*_column;i++){
        cout << _matrix[i] << endl;
    }
    return os;
}






template <typename Elemtype>
Matrix<Elemtype>::Matrix(Matrix &rhs){
  _row=rhs._row;
  _column=rhs._column;
  int mat_size=_row*_column;
  _matrix=new Elemtype[mat_size];
    for(int i=0;i<mat_size;i++){
      _matrix[i]=rhs._matrix[i];
    }
}




template <typename Elemtype>
Matrix<Elemtype> operator<<(ostream &os,Matrix<Elemtype> &m)
{
  m.print(os);
}
template <typename Elemtype>
Matrix<Elemtype> operator+(Matrix<Elemtype> &m,Matrix<Elemtype> &m2)
  {
    int temp1=m.row();
    int temp2=m.column();
    Elemtype temp3=Elemtype();
    Matrix<Elemtype> result(temp1,temp2);

    for(int i=0;i<temp1;i++)
      for(int j=0;j<temp2;j++)
        {
          temp3=m(i,j);
          temp3+=m2(i,j);
          result.resetelem(i,j,temp3);
        }

        return result;

  };


int main()
{
  double value;
class Matrix<double> t(4,4);
 double Array[16];
 for(int i=0;i<16;i++)
   {
     Array[i]=i;
   }
t.print(cout);
Matrix<double> t2(4,4);

 for(int i=0;i<t2.row();i++)
   for(int j=0;j<t2.column();j++)
   {
       value=Array[i*t2.row()+j];
       t2.resetelem(i,j,value);
         }

 cout << t2;

Matrix<double> t3(4,4);
 cout << t3;
t3= t+t2;
 cout << t3;
 return 0;
}



reply via email to

[Prev in Thread] Current Thread [Next in Thread]