- 了解运算符重载的实际意义。
- 掌握运算符重载的规则。
- 熟悉多种运算符重载的实际应用。
题目:定义复数类Complex,利用运算符重载实现复数的加、减、乘、除四则运算。
要求:
- 复数类包括实部()和虚部()两个数据成员,可以分别读取、设置和输出。
- 每个运算测试组数据。
注意程序的健壮性,如除零操作。
原理:
- 加法规则,。
- 减法规则,。
- 乘法规则,。
- 除法规则,
提高(选做):通过运算符重载实现两个复数和之间的关系运算,包括大于(若则)、小于(若则)、等于(若且则)、不等于(若或则)。
#include <iostream>
using namespace std;
class Complex {
public:
//构造函数
Complex(double r = 0.0, double i = 0.0) :real(r), image(i) {}
//键入复数
void set() {
cin >> real >> image;
}
//复数加法
Complex operator+ (const Complex &c2) const {
return Complex(real + c2.real, image + c2.image);
}
//复数减法
Complex operator- (const Complex &c2) const {
return Complex(real - c2.real, image - c2.image);
}
//复数乘法
Complex operator* (const Complex &c2) const {
return Complex(real*c2.real - image * c2.image, real*c2.image + image * c2.real);
}
//复数除法
Complex operator/ (const Complex &c2) const {
if (!c2.real && !c2.image) {
exit(-1);
}
return Complex((real*c2.real + image * c2.image) / (c2.real*c2.real + c2.image*c2.image),
(image * c2.real - real * c2.image) / (c2.real*c2.real + c2.image*c2.image));
}
//比较运算>
bool operator> (Complex &c2){
if ((real*real + image * image) > (c2.real*c2.real + c2.image*c2.image)) {
return true;
}
else {
return false;
}
}
//比较运算<
bool operator< (Complex &c2) {
if ((real*real + image * image) < (c2.real*c2.real + c2.image*c2.image)) {
return true;
}
else {
return false;
}
}
//比较运算==
bool operator== (Complex &c2) {
if (real == c2.real&&image == c2.image) {
return true;
}
else {
return false;
}
}
//比较运算!=
bool operator!= (Complex &c2) {
if (real != c2.real||image != c2.image) {
return true;
}
else {
return false;
}
}
//输出显示
void display() const{
cout << real << "+" << image << "i";
}
private:
double real, image;
};
int main()
{
Complex c1, c2, c3, c4, c5, c6;
cout << "请分别输入c1,c2:";
c1.set();
c2.set();
cout << "c1 = "; c1.display(); cout << endl;
cout << "c2 = "; c2.display(); cout << endl;
cout << endl;
//四则运算
c3 = c1 + c2;
cout << "c1 + c2 = "; c3.display(); cout << endl;
c4 = c1 - c2;
cout << "c1 - c2 = "; c4.display(); cout << endl;
cout << endl;
c5 = c1 * c2;
cout << "c1 * c2 = "; c5.display(); cout << endl;
c6 = c1 / c2;
cout << "c1 / c2 = "; c6.display(); cout << endl;
cout << endl;
//比较c3、c4大小
if (c3 > c4) {
c3.display(); cout << " > "; c4.display();
}
else if (c3 < c4) {
c3.display(); cout << " < "; c4.display();
}
else {
c3.display(); cout << " = "; c4.display();
}
cout << endl;
//c5、c6是否相等
if (c5 == c6) {
c5.display(); cout << " = "; c6.display();
}
else {
c5.display(); cout << " ≠ "; c6.display();
}
cout << endl;
system("pause");
return 0;
}
测试数据一
测试数据二
测试数据三
来源:CSDN
作者:LeopoldZhang2000
链接:https://blog.csdn.net/LeopoldZhang2000/article/details/104310904