设计一个RMB类(人民币类),并通过对“+”、“”运算符重载实现直接利用“+”、“”求人民币存款利息的功能。
#include<iostream>
using namespace std;
class RMB
{
public:
RMB(double t, double l, double b, double li) : time(t=1), lilv(l=0.2), bengjin(b=10000), lixi(li=0) {};
RMB operator+(RMB z);
RMB operator*(RMB z);
void display(RMB z);
protected:
private:
double time;//时间单位为年
double lilv;//为年利率
double bengjin;
double lixi;
};
RMB RMB::operator+(RMB z)
{
RMB temp(0,0,0,0);
temp.bengjin = bengjin + z.bengjin;
temp.time = time + z.time;
return temp;
}
RMB RMB::operator*(RMB z)
{
RMB temp(0,0,0,0);
temp.lixi = z.time * z.lilv *z.bengjin;
return temp;
}
void RMB::display(RMB z)
{
cout << "存款利息为:" << z.lixi << endl;
}
void main()
{
RMB a(1, 0.2, 20000, 0), b(1, 0.2, 20000, 0);
RMB c(0, 0, 0, 0);
c = a + b;
c = a * b;
c.display(c);
}
设计一个矩阵类,要求在矩阵类中重载“+”、“-”、“*”、“=”运算符。
#include<iostream>
using namespace std;
class jvzheng
{
public:
jvzheng()
{
int j, k = 0;
cout << "请输入矩阵的元素:" << endl;
for (j = 0; j < 3; j++)
{
for (k = 0; k < 3; k++)
{
cin >> a[j][k];
}
}
}
jvzheng operator+(jvzheng x);
jvzheng operator-(jvzheng x);
jvzheng operator*(jvzheng x);
jvzheng operator/(jvzheng x);
jvzheng operator=(jvzheng x);
void display( );
protected:
private:
double a[3][3];
};
jvzheng jvzheng::operator+(jvzheng x)
{
int i, j;
jvzheng temp;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
temp.a[i][j] = a[i][j] + x.a[i][j];
}
}
return temp;
}
jvzheng jvzheng::operator-(jvzheng x)
{
int i, j;
jvzheng temp;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
temp.a[i][j] = a[i][j] - x.a[i][j];
}
}
return temp;
}
jvzheng jvzheng::operator*(jvzheng x)
{
int i, j, k, l;
jvzheng temp;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
for (k = 0; k < 3; k++)
{
for (l = 0; l < 3; l++)
{
temp.a[i][j] += a[k][l] * x.a[l][k];
}
}
}
}
return temp;
}
jvzheng jvzheng::operator/(jvzheng x)
{
jvzheng temp;
double b[3][6];
double c[3][3];
double d[3][3];
int i, j;
for (i = 0; i < 3; i++)//矩阵的转置
{
for (j = 0; j < 3; j++)
{
c[i][j] = a[j][i];
}
}
double zhi;
zhi = a[1][1] * a[2][2] * a[3][3] + a[1][2] * a[2][3] * a[3][1] + a[1][3] * \
a[2][1] * a[3][2] - a[3][3] * a[2][1] * a[1][3] - a[3][2] * a[2][3] * \
a[1][1] - a[3][1] * a[2][2] * a[1][3]; //矩阵的行列式的值
for (i = 0; i < 3; i++) //矩阵的逆
{
for (j = 0; j < 0; j++)
{
c[i][j] = c[i][j] / zhi;
}
}
int k, l;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
for (k = 0; k < 3; k++)
{
for (l = 0; l < 3; l++)
{
temp.a[i][j] += c[k][l] * x.a[l][k];
}
}
}
}
return temp;
}
jvzheng jvzheng::operator=(jvzheng x)
{
int j, k = 0;
for (j = 0; j < 3; j++)
{
for (k = 0; k < 3; k++)
{
cin >> x.a[j][k];
}
}
return x;
}
void jvzheng::display( )
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
cout << a[i][j] << "\t";
}
cout << endl;
}
}
void main()
{
jvzheng a, b,c;
c = a + b;
cout << "a+b=" << endl;
c.display();
c = a - b;
cout << "a-b=" << endl;
c.display();
c = a * b;
cout << "a*b=" << endl;
c.display();
c = a / b;
cout << "a/b=" << endl;
c.display();
}
如有错误,请多多指教。