十分注意:在重载操作符的时候,一定要返回相应值,否则会出现莫名的内存问题,而且编译的时候不会提示!
这里重载了<<,>>,==,!=,=,().
#include
<
iostream
>
#include
<
stdlib.h
>
#include
<
errno.h
>
using
namespace
std;

class
myclass

...
{
public:
int row,col;
private:
int *p;
int total;
public:
myclass(int a,int b);
const int Get(int,int);
int Put(int,int,int);
friend ostream & operator<<(ostream& output,myclass a);
friend istream & operator>>(istream& input,myclass a);
friend bool operator ==(myclass a,myclass b);
friend bool operator !=(myclass a,myclass b);
void operator= (myclass a);
int& operator() (int m,int n);
const int& operator()(int m,int n)const;
}
;


int
&
myclass::
operator
()(
int
m,
int
n)

...
{
if( !(m<row && m>=0 && n>=0 && n<col) ) exit(0);
int pp=5*m+n;
return p[pp];
}
const
int
&
myclass::
operator
()(
int
m,
int
n)
const

...
{
if( !(m<row && m>=0 && n>=0 && n<col) ) exit(0);
int pp=5*m+n;
return p[pp];
}
void
myclass::
operator
=
(myclass a)

...
{
int i=0,j=0;
for(i=0;i<a.row;i++)
for(j=0;j<a.col;j++)Put(i,j,a.Get(i,j));
}

bool
operator
!=
(myclass a,myclass b)

...
{
return !(a==b);
}
bool
operator
==
(myclass a,myclass b)

...
{
int i=0,j=0;
for(i=0;i<a.row;i++)
for(j=0;j<a.col;j++)
if(a.Get(i,j) != b.Get(i,j))return false;
return true;
}
ostream
&
operator
<<
(ostream
&
output,myclass qq)

...
{
int i=0,j=0;

for(i=0;i<qq.row;i++)...{

for(j=0;j<qq.col;j++)...{
output<<qq(i,j)<<" ";
}
output<<endl;
}
return output;
}
istream
&
operator
>>
(istream
&
input,myclass a)

...
{
int i=0,j=0;
int temp=0;

for(i=0;i<a.row;i++)...{

for(j=0;j<a.col;j++)...{
input>>temp;
a.Put(i,j,temp);
}
}
return input;
}

myclass::myclass(
int
a,
int
b)

...
{
row = a;
col = b;
total=a*b;
p = new int[total];
}
const
int
myclass::Get(
int
m,
int
n)

...
{

if( !(m<row && m>=0 && n>=0 && n<col) )...{ perror("out of range~~");exit(0);}
int pp=5*m+n;
return p[pp];
}
int
myclass::Put(
int
m,
int
n,
int
val)

...
{
if( !(m<row && m>=0 && n>=0 && n<col) ) exit(0);
int pp=5*m+n;
p[pp]=val;
}



main()

...
{
int i,j;
myclass my1(6,5),my2(6,5);
cout<<"please input my1 ";
cin>>my1;
cout<<"please input my2 ";
cin>>my2;
cout<<"using opreator output,my1:"<<endl;
cout<<my1;
cout<<"using opreator output,my2:"<<endl;
cout<<my1;
if(my1==my2)cout<<"my1==my2"<<endl;
if(my1!=my2)cout<<"my1!=my2"<<endl;
cout<<"++++++++++++++++++++++++++++++++++"<<endl;
cout<<"please input my2 ";
cin>>my2;
cout<<"my2:"<<endl;
cout<<my2;

if(my1==my2)cout<<"my1==my2"<<endl;
if(my1!=my2)cout<<"my1!=my2"<<endl;
cout<<"now let my2=my1"<<endl;
my2=my1;
cout<<"my2:"<<endl;
cout<<my2<<endl;
if(my1==my2)cout<<"my1==my2"<<endl;
if(my1!=my2)cout<<"my1!=my2"<<endl;
cout<<"output my1 by my1(i,j)"<<endl;

for(i=0;i<my1.row;i++)...{

for(j=0;j<my1.col;j++)...{
cout<<my1(i,j)<<" ";
}
cout<<endl;
}

system("pause");
}