加法还可用友元函数,两个参数的方式实现。
#include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; class Matrix { public: Matrix(){memset(this->_mat,0,sizeof(this->_mat));} Matrix(float tmp[4][4] ) { for (int i=0;i<4;i++) for(int j=0;j<4;j++) _mat[i][j]=tmp[i][j]; } Matrix(const Matrix *tmp) { memcpy(this->_mat,tmp->_mat,sizeof(tmp->_mat)); } // Matrix operator+(Matrix &a,Matrix &b) // { // Matrix result(a); // return result+=b; // // } Matrix operator+(Matrix &a) { Matrix tmp(this); tmp+=a; return tmp; } void operator+=(const Matrix &b) const { for (int i=0;i<4;i++) for(int j=0;j<4;j++) _mat[i][j]+=b._mat[i][j]; } float& operator() (int , int ); float operator() (int rwo,int colum) const; void print() const { for (int i=0;i<4;i++) { for(int j=0;j<4;j++) { cout<<_mat[i][j]<<" "; } cout<<endl; } } private: mutable float _mat[4][4]; }; //float Matrix::operator ()(int r,int c) const //{ // return this->_mat[r][c]; //} float& Matrix::operator ()(int r,int c) { return this->_mat[r][c]; } int main() { Matrix a,b; float tmp[4][4]={{0,1,2,3},{1,2,3,4},{2,3,4,5},{3,4,5,6}}; Matrix aa(tmp); Matrix c(aa); c.print(); cout<<c(1,3); c(1,3)=5; cout<<c(1,3)<<endl; b.print(); aa+=aa; aa.print(); a=aa+ b; a.print(); }