运算符重载:复数的+、-、*运算
描述
设计一个复数类 Complex 并实现复数的+、-、* 三种运算。
在下面代码的注释 Begin End之间完成代码:
#include <iostream>
using namespace std;
/********* Begin *********/
class Complex {
//复数类的声明
};
//复数类的定义
/********* End *********/
int main() {
float a, b, c, d;
cin >> a >> b >> c >> d;
Complex c1(a, b), c2(c, d);
cout << "c1 = ";
c1.Print();
cout << "c2 = ";
c2.Print();
cout << "c1 + c2 = ";
(c1 + c2).Print();
cout << "c1 - c2 = ";
(c1 - c2).Print();
cout << "c1 * c2 = ";
(c1 * c2).Print();
}
输入
输入两个复数(数据分为两组,前两个和后两个数分别表示一个复数 c1 和 c2,即c1=1+1i
,c2=2+2i
)
输出
第1个复数
第2个复数
复数的和
复数的差
复数的乘积
输入输出示例
输入 | 输出 | |
示例 1 | 1 1 2 2 | c1 = 1+1i c2 = 2+2i c1 + c2 = 3+3i c1 - c2 = -1-1i c1 * c2 = 0+4i |
平均代码量53 行
#include <iostream>
using namespace std;
/********* Begin *********/
class Complex {
//复数类的声明
double real,imag;
public:
Complex(double r=0,double i=0):real(r),imag(i){}
Complex operator+(Complex& a);
Complex operator-(Complex& a);
Complex operator*(Complex& a);
void Print();
};
//复数类的定义
Complex Complex::operator+(Complex& a) {
//1
// Complex temp;
//temp.real = real + a.real;
//temp.imag = imag + a.imag;
// return temp;
//2
return Complex(real + a.real, imag + a.imag);
}
Complex Complex:: operator-(Complex &a){
//1
// Complex temp;
// temp.real = real-a.real;
// temp.imag = imag - a.imag;
// return temp;
//2
return Complex(real-a.real,imag-a.imag);
}
Complex Complex::operator*(Complex &a){
//1
//Complex temp;
// temp.real = real*a.real-imag*a.imag;
// temp.imag = imag*a.real+real*a.imag;
// (a+bi) (c+di)= (ac-bd)+ (bc+ad)i
// return temp;
//2
return Complex(real*a.real-imag*a.imag, imag*a.real+real*a.imag);
}
void Complex:: Print(){
cout<<real;
if(imag<0)
cout<<imag<<"i"<<endl;
else
cout<<"+"<<imag<<"i"<<endl;
}
/********* End *********/
int main() {
float a, b, c, d;
cin >> a >> b >> c >> d;
Complex c1(a, b), c2(c, d);
cout << "c1 = ";
c1.Print();
cout << "c2 = ";
c2.Print();
cout << "c1 + c2 = ";
(c1 + c2).Print();
cout << "c1 - c2 = ";
(c1 - c2).Print();
cout << "c1 * c2 = ";
(c1 * c2).Print();
}