您的位置:首页 > 编程语言 > C语言/C++

C++学习笔记----------运算符的重载

2019-06-13 15:51 1551 查看

C++中允许对运算符进行重载是区别于C语言的一大优化功能,但它也有自身的限制,下面让我们一起来看看吧!

实验1:定义一个复数类Complex,重载“++”运算符,使之能用于复数的自加即实部和虚部分别自加,用成员函数实现;重载“+”和“-”运算符,使之能用于复数的加法和复数的减法运算,用友元函数实现。

  • 重载“++”运算符:用成员函数实现:
#include <iostream>
using namespace std;

class Complex
{

private:

int real,imag;

public:

Complex(){real=0;imag=0;}//无参构造函数

Complex(int r,int i){real=r;imag=i;}//有参构造函数

void print()
{
cout<<real;
if(imag>=0)
{cout<<"+";}
cout<<imag<<"i"<<endl;
}

//前置自增
Complex operator++()
{
Complex c;
c.real=++(this->real);
c.imag=++imag;
return c;
}

//后置自增
Complex operator++(int)
{
/*Complex c;
c.real=(this->real)++;
c.imag=imag++;
return c;*/
Complex c=*this;
real++;
imag++;
return c;
}

};

int main()
{

Complex c1(1,1),c2(2,-2),c3,c4,c5;
c1.print();
c3.print();
c4=c2++;
c5=++c1;//成员函数实现 c1.operator++() this
c4.print();
c5.print();

return 0;
}
  • 重载“+”和“-”运算符:用友员函数实现:
#include <iostream>
using namespace std;

class Complex
{

private:

int real,imag;
public:

Complex(){real=0;imag=0;}//无参构造函数

Complex(int r,int i){real=r;imag=i;}//有参构造函数

friend Complex operator-(Complex cc1,Complex cc2)//c4=c1-c2
{
Complex c;
c.real=cc1.real-cc2.real;
c.imag=cc1.imag-cc2.imag;
return c;
}
/*
friend Complex operator-(Complex &cc1,Complex &cc2)//c4=c1-c2
{
return Complex(cc1.real-cc2.real ,cc1.imag -cc2.imag );
}
*/

friend Complex operator+(Complex cc1,Complex cc2)//c5=c1+c2
{
Complex c;
c.real=cc1.real+cc2.real;
c.imag=cc1.imag+cc2.imag;
return c;
}

void print()
{
cout<<real;
if(imag>=0){cout<<"+";}
cout<<imag<<"i"<<endl;
}

};

int main()
{
Complex c1(1,1),c2(2,-2),c3,c4,c5;
c1.print();
c3.print();
c4=c1-c2;//operator-(c1,c2);
c4.print();
c5=c1+c2;//operator+(c1,c2);
c5.print();
return 0;
}

实验2:
编写程序,重载运算符“+”和“-”,对两个矩阵进行加法、减法运算。

#include <iostream>
using namespace std;
int i,j;

class Matrix
{

private:

int matrix[3][3];

public:

void show();

Matrix();//无参构造函数

Matrix operator + (Matrix &m1);
Matrix operator - (Matrix &m1);
};

Matrix::Matrix()
{
for(i=0;i<3;i++)
for(j=0;j<3;j++)
matrix[i][j]=rand()%20;
}

Matrix Matrix::operator+(Matrix &m1)
{
Matrix tmp;
for( i=0;i<3;i++)
for( j=0;j<3;j++)
tmp.matrix [i][j]=matrix[i][j]+m1.matrix [i][j];
return tmp;
}

Matrix Matrix::operator-(Matrix &m1)
{
Matrix tmp;
for( i=0;i<3;i++)
for( j=0;j<3;j++)
tmp.matrix [i][j]=matrix[i][j]-m1.matrix [i][j];
return tmp;
}

void Matrix::show()
{
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
cout<<matrix[i][j]<<'\t';
cout<<endl;
}
cout<<endl;
}

void main()
{
Matrix m1,m2,m3,m4;
m3=m1+m2;
m4=m1-m2;
m1.show ();
m2.show();
cout<<"Matrix m1+m2="<<endl;
m3.show ();
cout<<"Matrix m1-m2="<<endl;
m4.show ();
return ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: