网易云音乐链接 : 点我听歌.
1、定义复数类的加法与减法,使之能够执行下列运算:
complex a(2,5),b(7,8),c(0,0);
c=a+b;
c=4.1+a;
c=b-5.6;
代码
#include <iostream.h>
#include <string.h>
//using namespace std;
class Complex
{
double real;
double imag;
public:
Complex()
{
real=0.0; imag=0.0;}
Complex(double r, double i)
{
real = r; imag = i;}
void show()
{
cout<<real<<" + "<<imag<<"i"<<endl;}
Complex operator+(const Complex &y) //做为成员函数-对象加法
{
Complex t(0,0);
t.real = real + y.real;
t.imag = imag + y.imag;
return t;
}
Complex operator-(const Complex &y1) //做为成员函数-对象减法
{
Complex t(0,0);
t.real = real - y1.real;
t.imag = imag - y1.imag;
return t;
}
Complex operator+(const double v)
{
Complex t(0,0);
t.real = v + real;
t.imag = imag;
return t;
}
Complex operator-(const double v1)
{
Complex t(0,0);
t.real = v1 - real;
t.imag = -imag;
return t;
}
friend Complex operator-(double, Complex &);
friend Complex operator+(double, Complex &);
};
Complex operator+(double c1, Complex &c2)
{
Complex c;
c.real=c2.real+c1;
c.imag=c2.imag;
return c;
}
Complex operator-(double c1, Complex &c2)
{
Complex c;
c.real=c1-c2.real;
c.imag=-c2.imag;
return c;
}
void main()
{
Complex a(2, 5);Complex b(7, 8);Complex c;
c = a + b;
c.show();
c = 4.1 + a;
c.show();
c=b-5.6;
c.show();
}
运行结果
◇ 2、设计一个2行3列的矩阵类,重载运算符“+”和“-”,能实现矩阵类对象的加减运算;重载流插入运算符“<<”和流提取运算符“>>”,使之能用于矩阵的输入和输出。
代码
#include <iostream.h>
class matrix
{
private:
int a[2][3];
public:
friend matrix operator+(matrix&A, matrix&B);
friend ostream& operator<<(ostream&, matrix&);
friend istream& operator>>(istream&, matrix&);
matrix(){
};
};
matrix operator+(matrix&A,matrix&B)
{
matrix c;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
c.a[i][j]=A.a[i][j]+B.a[i][j];
return c;
}
istream & operator >> (istream &input,matrix &a)
{
cout<<"请输入矩阵: "<<endl;
for(int i=0;i<2;i++)
for(int j=0;j<3;j++)
input>>a.a[i][j];
return input;
}
ostream & operator << (ostream &output,matrix &C)
{
cout<<"矩阵相加的结果为:"<<endl;
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
output<<C.a[i][j]<<" ";
cout<<endl;
}
return output;
}