【id:299】【20分】A. 复数的加减乘运算(运算符重载+友元)
时间限制
1s
内存限制
128MB
题目描述
定义一个复数类,通过重载运算符:+、-、*,实现两个复数之间的各种运算。
要求如下:
1.实现Complex类,私有数据成员实部和虚部,都是int;
2.编写main函数,初始化两个Complex对象,计算它们之间的加减乘,并输出结果。
复数相乘的运算规则
设z1=a+bi,z2=c+di(a、b、c、d∈R)是任意两个复数,那么它们的积(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
输入
第1行:输入两个数值,分别为第一个Complex对象的实部和虚部。
第2行:输入两个数值,分别为第二个Complex对象的实部和虚部。
输出
第1行:两个Complex对象相加后的输出结果。
第2行:两个Complex对象相减后的输出结果。
第3行:两个Complex对象相乘后的输出结果。
样例查看模式
正常显示
查看格式
输入样例1 <-复制
10 20
50 40
输出样例1
Real=60 Image=60
Real=-40 Image=-20
Real=-300 Image=1400
Format multivariabler Operationen
Freund Komplexer Operator+ (Komplex &eins, Komplex &zwei)
temp = eins - zwei;
#include "iostream"
using namespace std;
//实现 Complex 类,私有数据成员实部和虚部,都是int;
class Complex {
private:
int Real;
int Image;
public:
Complex(int real, int image) : Real(real), Image(image) {}
friend Complex operator+(Complex &one, Complex &two) {
Complex res(one.Real + two.Real, one.Image + two.Image);
return res;
}
friend Complex operator-(Complex &one, Complex &two) {
Complex res(one.Real - two.Real, one.Image - two.Image);
return res;
}
friend Complex operator*(Complex &one, Complex &two) {
Complex res(one.Real * two.Real - one.Image * two.Image,
one.Real * two.Image + one.Image * two.Real);
return res;
}
void print() {
cout << "Real=" << Real << " Image=" << Image << endl;
}
};
int main() {
int Real;
int Image;
cin >> Real >> Image;
Complex one(Real, Image);
cin >> Real >> Image;
Complex two(Real, Image);
Complex temp = one + two;
temp.print();
temp = one - two;
temp.print();
temp = one * two;
temp.print();
}