一运行,你猜怎么着?
matrix.h
- C/C++ code
#ifndef _MATRIX_H#define _MATRIX_H#include<cassert>#include<iostream>using namespace std;template<class T>class matrix{ int rows;//行数 int cols;//列数 T* start;public: int getRows(){return rows;} int getCols(){return cols;} matrix():start(NULL),rows(0),cols(0){} matrix(int a,int b):rows(a),cols(b){start=new T[rows*cols];init(T());} template<class T1> matrix(matrix<T1>& a):rows(a.getRows()),cols(a.getCols()),start(new T[rows*cols]){ for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ (*this)(i,j)=a(i,j); } } } void init(T t){//初始化 for(int i=0;i<rows*cols;i++){ start[i]=t; } } T& operator()(int i,int j){//获取i行j列的值 return start[i*cols+j]; } T const& operator()(int i,int j)const{ return start[i*cols+j]; } template<class T1> matrix<T>& operator=(matrix<T1>& a){//赋值函数 if(start!=NULL){ delete []start; } rows=a.getRows(); cols=a.getCols(); start=new T[rows*cols]; for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ (*this)(i,j)=a(i,j); } } return *this; } template<class T1> friend matrix<T1> operator+(matrix<T1>& m1,matrix<T1>& m2); void print(){ for(int i=0;i<rows;i++){ for(int j=0;j<cols;j++){ cout<<(*this)(i,j)<<" "; } cout<<endl; } } ~matrix(){ if(start!=NULL){ delete []start; } start=NULL; }}; template<class T>matrix<T> operator+(matrix<T>& m1,matrix<T>& m2){ assert(m1.getRows()==m2.getRows() && m1.getCols()==m2.getCols()); matrix<T> result(m1.getRows(),m1.getCols()); for(int i=0;i<m1.getRows();i++){ for(int j=0;j<m1.getCols();j++){ result(i,j)=m1(i,j)+m2(i,j); cout<<"result("<<i<<","<<j<<")= "<<result(i,j)<<endl; } } return result;} #endif
matrix_test.cpp
- C/C++ code
#include<iostream>#include "matrix.h"using namespace std;int main(){ matrix<int> a(2,2); a(0,0)=0; a(0,1)=2; a(1,0)=3; a(1,1)=4; matrix<int> b(2,2); b(0,0)=1; b(0,1)=0; b(1,0)=0; b(1,1)=5; b=a; matrix<int> c; c=a+b; a.print();cout<<endl; b.print();cout<<endl; c.print();cout<<endl; system("pause");}
一运行,你猜怎么着?
c(0,0)
c(0,1)出错
c(1,0)
c(1,1)没问题
[解决办法]
拷贝构造函数和赋值构造函数分别写错下面那样:
matrix(matrix<T>& a):rows(a.getRows()),cols(a.getCols()),start(new T[rows*cols]){
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
(*this)(i,j)=a(i,j);
}
}
}
matrix<T>& operator=(matrix<T>& a){//赋值函数
if(start!=NULL){
delete []start;
}
rows=a.getRows();
cols=a.getCols();
start=new T[rows*cols];
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
(*this)(i,j)=a(i,j);
}
}
return *this;
}
[解决办法]
返回函数内的局部变量本身就是不靠谱的,应该用引用的方式返回,这样局部变量不会被释放
[解决办法]