您的位置:首页 > 编程语言 > C语言/C++

C++复数类对除法运算符 / 的重载

2015-05-21 20:24 260 查看

C8-1 复数加减乘除

(100.0/100.0 points)
题目描述
求两个复数的加减乘除。输入描述第一行两个double类型数,表示第一个复数的实部虚部第二行两个double类型数,表示第二个复数的实部虚部输出描述输出依次计算两个复数的加减乘除,一行一个结果输出复数先输出实部,空格,然后是虚部,样例输入
1 1
3 -1
样例输出
4 0
-2 2
4 2
0.2 0.4
 #include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;class Complex{
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {};
Complex operator+ (const Complex &c2) const;
Complex operator- (const Complex &c2) const;/*实现下面三个函数*/
Complex operator* (const Complex &c2) const;
Complex operator/ (const Complex &c2) const;
friend ostream & operator<< (ostream &out, const Complex &c);private:
double real;
double imag;
};Complex Complex::operator+ (const Complex &c2) const {
return Complex(real + c2.real, imag + c2.imag);
}Complex Complex::operator- (const Complex &c2) const {
return Complex(real - c2.real, imag - c2.imag);
}Complex Complex::operator* (const Complex &c2) const
{
return Complex(real*c2.real - imag*c2.imag, real*c2.imag + imag*c2.real);
}Complex Complex::operator/ (const Complex &c2) const
{
if (c2.imag == 0)
return Complex(real / c2.real, imag / c2.real);
else
return (*this)*Complex(c2.real, -c2.imag) / Complex(c2.real*c2.real + c2.imag*c2.imag, 0);
}ostream & operator<< (ostream &out, const Complex &c)
{
out << c.real << " " << c.imag << endl;
return out;
}int main() {
double real, imag;
cin >> real >> imag;
Complex c1(real, imag);
cin >> real >> imag;
Complex c2(real, imag);
cout << c1 + c2;
cout << c1 - c2;
cout << c1 * c2;
cout << c1 / c2;
}
就是C++对操作符的重载。有两个地方要注意:1、对 << 的重载中,注意要返回 out,这样就可以实现 << 的级联输出(多项并列时);2、对 / 的重载中,注意 return (*this)*Complex(c2.real, -c2.imag) / Complex(c2.real*c2.real + c2.imag*c2.imag, 0); 这一句是会继续调用这个重载函数本身的!它本身就是对 / 的重载,而你在这里又用到了 / ,所以会递归下去!所以必须加 return Complex(real / c2.real, imag / c2.real); 让递归归于平凡的情形(实际上只会递归一层)。

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: