#include<iostream>
#define MAX 10
using namespace std;
class matrix;
matrix& operator-(matrix& b,const matrix& c);
class matrix
{
private:
int row,col,(*a)[MAX];
public:
matrix(){}
matrix(int r,int c,int (*b)[MAX]):row(r),col(c),a(b){}
matrix& operator+(const matrix& b)
{
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
a[i][j]=a[i][j]+b.a[i][j];
return *this;
}
friend matrix& operator-(matrix& b,const matrix& c)
{
for(int i=0;i<b.row;i++)
for(int j=0;j<b.col;j++)
b.a[i][j]=b.a[i][j]-c.a[i][j];
return b;
}
void show()
{
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
}
};
void main()
{
int row =2 ,col =3,a[2][MAX]={{1,2,3},{4,5,6}};
matrix mat1(row,col,a);
int b[2][MAX]={{4,3,2},{1,2,3}};
matrix mat2(row,col,b);
matrix mat3;
mat3 = mat1 + mat2;
cout<<"mat3"<<endl;
mat3.show();
cout<<"mat1"<<endl;
mat1.show();
cout<<"mat4"<<endl;
matrix mat4;
mat4 = mat1 - mat2;
mat4.show();
}
重载例子:
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
#define N 20
class CBook
{
private:
char name[N];
double price;
public:
CBook(char* n,double p){strcpy(name,n);price=p;}
CBook(const CBook&c)
{
strcpy(name,c.name);
price = c.price;
}
CBook&operator=(const CBook s)
{
strcpy(name,s.name);
price = s.price;
return *this;
}
char& operator[](int i)
{
if(i>=0)
return name[i];
return name[N-1];
}
bool operator>(const CBook c)
{
return price>c.price;
}
friend istream& operator>>(istream& in,CBook& c)
{
in>>c.price;
return in;
}
friend ostream& operator<<(ostream& out,CBook c)
{
out<<c.name<<" "<<c.price<<endl;
return out;
}
~CBook()
{
}
};
void main()
{
CBook hlm("红楼梦", 34.5), sgyy("三国演义", 45.6), xinshu = sgyy;
cin >> hlm >> sgyy;
cout << hlm << sgyy;
if (hlm > sgyy)
cout << "红楼梦比三国演义贵\n";
else
cout << "红楼梦比三国演义便宜\n";
cout << xinshu;
xinshu[-2] = '1';
xinshu[10] = '1';
xinshu[0] = '1';
cout << xinshu;
}