X& X::operator=(const X& source){
}
友元运算符函数的原型在类内部声明格式:
类内部:
Class X{
//
friend 返回类型 operator运算符(形参表);
//
}
类外部:
返回类型 operator运算符(形参表)
{
函数体
}
成员运算符函数定义的语法形式
类内部:
class X{
//
返回类型 operator运算符(形参表);
//
}
返回类型 X::operator运算符(形参表)
{
函数体
}
复数:
class complex{
public:
double real,imag;
complex operator+(complex om1,complex om2) {
complex temp;
temp.real = om1.real + om2.real;
temp.imag = om1.imag + om2.imag;
return temp;
}
complex operator++(){ //operator++(ob) ob为complex类引用对象
++real;
++imag;
return *this;
}
complex operator++(0){ //operator++(ob,0)
real++;
imag++;
return *this;
}
complex(double r=0, double i=0){
real = r;
imag = i;
}
}
矩阵加法重载;矩阵输出重载
#include <iostream>
using namespace std;
class CMatrix23
{
private:
int a[2][3];
public:
CMatrix23 operator + ( const CMatrix23& mat );
friend ostream& operator << ( ostream& os,const CMatrix23& mat );
friend istream& operator >> ( istream& is,CMatrix23& mat );
};
CMatrix23 CMatrix23::operator + (const CMatrix23 &mat)
{
CMatrix23 tmp;
for( int i=0;i<2;++i )
{
for( int j =0;j<3;++j )
{
tmp.a[i][j] = this->a[i][j] + mat.a[i][j];
}
}
return tmp;
}
ostream& operator << ( ostream& os,const CMatrix23& mat )
{
for( int i=0;i<2;++i )
{
for( int j =0;j<3;++j )
{
os<<mat.a[i][j]<<" ";
}
os<<endl;
}
return os;
}
istream& operator >> ( istream& is,CMatrix23& mat )
{
for(int i=0;i<2;++i)
{
for(int j=0;j<3;++j)
{
cout<<"请输入第"<<i<<"行第"<<j<<"列的元素:";
is>>mat.a[i][j];
}
}
return is;
}
int main()
{
CMatrix23 mat1;
cin>>mat1;
cout<<mat1;
CMatrix23 mat2;
cin>>mat2;
cout<<mat2;
cout<<mat1+mat2<<endl;
return 0;
}