要求:
编写一个复数类complex,
用友元函数重载运算符 “+”,对两个复数进行加法操作。
用成员函数重载复合运算符 “*”,对两个复数进行乘法运算。
思路:
- 复数有实部real和虚部imag两个数据成员
- +和*均为双目运算符, 两种处理方式的参数个数不一样:运算符重载函数作为类的成员函数时,有一个参数是隐含的
#include<iostream>
using namespace std;
class Complex { //复数类
public:
Complex(double x, double y) :real(x),imag(y) {}
void dp() { //输出复数属性的函数
cout << "real: " << real << " imag: " << imag<<endl;
}
friend Complex operator+(Complex&c1,Complex&c2); //用友元函数重载运算符 +
Complex operator*(Complex&c1); //用类成员函数重载运算符 *
private:
double real, imag;
};
Complex operator+(Complex&c1, Complex&c2) {
return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
Complex Complex::operator*(Complex & c1) {
return Complex(c1.real*real, c1.imag*imag);
}
int main() {
Complex c1(3, 4), c2(5, 6), c3 = c1 + c2,c4=c1*c2;
c3.dp();
c4.dp();
return 0;
}
运行结果 ⬇