6-1
本题考虑对运算符进行重载。分别重载复数运算的+,-,*,/,=(赋值)运算符,以及比较大小的<=(复数1的模是否小于等于复数2的模)运算符,其中,比较运算符按复数的模进行比较。测试程序根据输入的mode值分别测试各个函数是否编写正确。
函数接口定义:
i#include <iostream>
using namespace std;
class Complex {
double real;
double imag;
public:
//构造函数
Complex(double real=0, double imag=0);
//operator+-*/=操作符函数
Complex operator+(const Complex& c) const;
Complex operator-(const Complex& c) const;
Complex operator*(const Complex& c) const;
Complex operator/(const Complex& c) const;
Complex operator=(const Complex& c);
//operator <=操作符函数
bool operator<=(const Complex& c) const;
//友元函数声明以帮助operator<<()函数访问Complex类的私有成员
friend ostream& operator<<(ostream& out, const Complex& c);
};
//n个复数,按模从小到达排序
void bubble_sort(Complex[],int n);
测试样例:
在这里给出函数被调用进行测试的例子:
int main() {
double dReal1, dImag1, dReal2, dImag2;
int mode;
cin>>mode;
cin>>dReal1>>dImag1>>dReal2>>dImag2;
Complex c1(dReal1, dImag1);
Complex c2(dReal2, dImag2);
Complex c[6] = {c1,c2,c1+c2,c1-c2,c1*c2,c1/c2};
switch(mode)
{
case 1: cout << c[0]<<" "<<c[1];break;
case 2: cout << c[2];break;
case 3: cout << c[3];break;
case 4: cout << c[4];break;
case 5: cout << c[5];break;
case 6: bubble_sort(c,6);
for(int i=0;i<6;i++)
cout<<c[i]<<" ";
}
return 0;
}
/* 请在这里填写答案 */
Complex::Complex(double real, double imag) {
this->real = real;
this->imag = imag;
}
Complex Complex::operator + (const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex Complex::operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
Complex Complex::operator*(const Complex& c) const {
return Complex(real*c.real-imag*c.imag,imag*c.real+real*c.imag);
}
Complex Complex::operator/(const Complex& c) const {
return Complex((real * c.real + imag * c.imag) / (c.real * c.real + c.imag * c.imag), (imag * c.real - real * c.imag) / (c.real * c.real + c.imag * c.imag));
}
Complex Complex::operator=(const Complex& c) {
return Complex(real=c.real,imag=c.imag);
}
bool Complex::operator<=(const Complex& c) const {
if ((real * real + imag * imag) <= (c.real *c. real + c.imag * c.imag)) {
return true;
}
else {
return false;
}
}
ostream& operator<<(ostream& out, const Complex& c) {
if (c.imag >= 0) {
return out << c.real<<"+" << c.imag << "i";
}
else {
return out << c.real<< c.imag << "i";
}
}
void bubble_sort(Complex fs[], int n) {
Complex temp;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i; j++) {
if (fs[j+1] <= fs[j])
{
temp = fs[j+1];
fs[j + 1] = fs[j];
fs[j] = temp;
}
}
}
}
①本题在重载<=运算符时需思考:究竟<=符号左边应是传入的值还是符号右边,也就是需要弄清楚谁应该是小值,谁应该是大值。显然由程序能看出符号右边为传入的值。
②重载运算符=时,自己偷懒随便写了参数,发现编译时使用mode=6s输出,始终得不到想要的结果,后重新修改正确重载=后,输出正常。
③冒泡排序算法n-1次外循环,内循环5!次。