C++ 10多态性 运算符重载
题目1
定义一个复数类complex, 数据成员包括: double real,image, 成员函数包括:构造函数、显示打印函数、重载+、*运算符的成员函数。
代码:
```#include "iostream"
using namespace std;
class complex
{
double real, image;
public:
complex(double r = 0, double i = 0)
{
real = r; image = i;
}
void show()
{
cout << real;
if (image>0)
cout << "+" << image << "i";
else
if (image<0)cout << image << "i";
cout << endl;
}
complex operator+(complex obj)
{
return complex(real+obj.real, image+obj.image);
}
complex operator*(complex obj)
{
return complex(real * obj.real - image * obj.image,real*obj.image+image*obj.real);
}
};
void main()
{
complex c1(1, 2), c2(2, 3), c3;
c3 = c1 + c2;
c3.show();
c3 = c1 * c2;
c3.show();
system("pause");
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200827220321112.png#pic_center)
## 题目2
定义一个复数类complex, 数据成员包括: double real,image, 成员函数包括:构造函数、显示打印函数。再定义二个友元函数,重载运算符减号“-”和负号“-”。
程序内容:
```cpp
//用成员函数重载运算符
#include "iostream"
using namespace std;
class complex
{
double real, image;
public:
complex(double r = 0, double i = 0)
{
real = r; image = i;
}
void show()
{
cout << real;
if (image>0)
cout << "+" << image << "i";
else
if (image<0)cout << image << "i";
cout << endl;
}
friend complex operator-(complex, complex);
friend complex operator-(complex);
};
complex operator-(complex c1, complex c2)
{
return complex(c1.real-c2.real,c1.image-c2.image);
}
complex operator-(complex c1)
{
return complex(-c1.real,-c1.image);
}
void main()
{
complex c1(1,1), c2(2,2), c3;
c3 = c1 - c2;
c3.show();
c3 = -c3;
c3.show();
system("pause");
}
题目3:
完善下面的程序,使用类的成员函数重载运算符+、
#include "iostream"
using namespace std;
class rmb //人民币
{
private:
int yan; //元
int jiao; // 分
public:
rmb(int y = 0, int j = 0)
{
yan=y;jiao=j;
}
// 此处编写显示打印函数
//此处编写重载运算符+函数
//此处编写重载运算符>函数
};
void main()
{
rmb r1(1,2),r2(3,4),r3;
r1.show();
r2.show();
r3=r1+r2;
r3.show();
cout << "==========================" << endl;
if (r1 > r2)
{
r1.show();
cout << "大于"<<endl;
r2.show();
}
else
{
r1.show();
cout << "不大于"<<endl;
r2.show();
}
system("pause");}
程序内容
#include "iostream"
using namespace std;
class rmb //人民币
{
private:
int yan; //元
int jiao; // 分
public:
rmb(int y = 0, int j = 0)
{
yan = y; jiao = j;
}
// 此处编写显示打印函数
void show()
{
cout << yan<<"元" ;
if (jiao > 0)
cout << jiao<<"角" ;
cout <<endl;
}
//此处编写重载运算符+函数
rmb operator+(rmb obj)
{
return rmb(yan + obj.yan, jiao + obj.jiao);
}
//此处编写重载运算符>函数
int operator>(rmb obj)
{
if (yan > obj.yan) return 1;
else if (yan == obj.yan && jiao > obj.jiao) return 1;
else return 0;
}
};
void main()
{
rmb r1(1, 2), r2(3, 4), r3;
r1.show();
r2.show();
r3 = r1 + r2;
r3.show();
cout << "==========================" << endl;
if (r1 > r2)
{
r1.show();
cout << "大于" << endl;
r2.show();
}
else
{
r1.show();
cout << "不大于" << endl;
r2.show();
}
system("pause");
}