
1、 设计一个复数类Complex,包括实部real和虚部image,设计3个友元函数,实现两个复数的加、减和乘法运算
展开全部
class Complex
{
public:
Complex(double r, double i):real(r),imag(i){}
void print();
friend Complex operator +(Complex, Complex);
friend Complex operator -(Complex, Complex);
friend Complex operator *(Complex, Complex);
private:
double real;
double imag;
};
void Complex::print()
{
cout << "(" << real << "+" << imag << "i)";
}
Complex operator +(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
Complex operator -(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real - c2.real;
c3.imag = c1.imag - c2.imag;
return c3;
}
Complex operator *(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real * c2.real - c1.imag * c2.imag;
c3.imag = c1.real * c2.imag + c1.imag * c2.real;
return c3;
}
void main()
{
Complex c1(2, 8), c2(4, 5), c3(0, 0), c4(0, 0), c5(0, 0);
c1.print();
cout << "+";
c2.print();
c3 = c1 + c2;
cout << "=";
c3.print();
cout << endl;
c1.print();
cout << "-";
c2.print();
c4 = c1 - c2;
cout << "=";
c4.print();
cout << endl;
c1.print();
cout << "*";
c2.print();
c5 = c1 * c2;
cout << "=";
c5.print();
}
{
public:
Complex(double r, double i):real(r),imag(i){}
void print();
friend Complex operator +(Complex, Complex);
friend Complex operator -(Complex, Complex);
friend Complex operator *(Complex, Complex);
private:
double real;
double imag;
};
void Complex::print()
{
cout << "(" << real << "+" << imag << "i)";
}
Complex operator +(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real + c2.real;
c3.imag = c1.imag + c2.imag;
return c3;
}
Complex operator -(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real - c2.real;
c3.imag = c1.imag - c2.imag;
return c3;
}
Complex operator *(Complex c1, Complex c2)
{
Complex c3(0, 0);
c3.real = c1.real * c2.real - c1.imag * c2.imag;
c3.imag = c1.real * c2.imag + c1.imag * c2.real;
return c3;
}
void main()
{
Complex c1(2, 8), c2(4, 5), c3(0, 0), c4(0, 0), c5(0, 0);
c1.print();
cout << "+";
c2.print();
c3 = c1 + c2;
cout << "=";
c3.print();
cout << endl;
c1.print();
cout << "-";
c2.print();
c4 = c1 - c2;
cout << "=";
c4.print();
cout << endl;
c1.print();
cout << "*";
c2.print();
c5 = c1 * c2;
cout << "=";
c5.print();
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |