定义一个复数类Complex,用成员函数重载加法运算符(+),用友元函数重载乘法运算符(),以适用对复数运算的要求。具体要求如下:
(1) 私有数据成员
● double real, iamge; real为实部,image为虚部。
(2) 公有成员函数
● Complex():无参构造函数,将real和image分别设置为0。
● Complex(double r,double i):有参构造函数,分别用r和i初始化real和image。
● Complex operator+(Complex &):用成员函数重载加法运算。
● void print():输出函数。如果real和image为都为0,则输出:0+0i;
(3)友元函数
● friend Complex operator(Complex &, Complex &):用友元函数重载乘法运算。
(4) 在主函数中定义三个复数对象c1(1,2)、c2(3,4)和c3,输出c1和c2,然后将c1+c2赋值给c3,输出c3,然后将c1*c2赋值给c3,输出c3。
输出示例:
1+2i
3+4i
4+6i
-5+10i
#include <iostream>
class Complex
{
public:
Complex() : _real(0.0), _image(0.0) {}
Complex(double real, double image) : _real(real), _image(image) {}
Complex operator+(const Complex &other) const
{
return Complex(_real + other._real, _image + other._image);
}
void print()
{
std::cout << _real << '+' << _image << 'i' << std::endl;
}
friend Complex operator*(const Complex &lhs, const Complex &rhs);
private:
double _real;
double _image;
};
Complex operator*(const Complex &lhs, const Complex &rhs)
{
double real = lhs._real * rhs._real - lhs._image * rhs._image;
double image = lhs._real * rhs._image + lhs._image * rhs._real;
return Complex(real, image);
}
int main()
{
Complex c1(1, 2), c2(3, 4);
c1.print();
c2.print();
Complex c3 = c1 + c2;
c3.print();
c3 = c1 * c2;
c3.print();
return 0;
}