C++ 定义一个复数类Complex重载运算符 “+”, “-”, “ * ”, “ / ”........................

来源:百度知道 编辑:UC知道 时间:2024/05/24 09:36:11
定义一个复数类Complex重载运算符 “+”, “-”, “ * ”, “ / ”, 使之能用于复数的加,减,乘,除。运算符重载函数作为Complex类的成员函数。编程序,分别求两个复数的和,差,积,商。

#include <iostream>

using namespace std;

class CComplex
{
private:
float real, image;
public:
CComplex() { }
CComplex( float r, float img ) { real = r; image = img; }
CComplex( CComplex& another )
{
real = another.real;
image = another.image;
}

CComplex &operator = (CComplex &another )
{
real = another.real;
image = another.image;
return *this;
}

CComplex operator +( CComplex & another )
{
return CComplex( real+ another.real, image + another.image );
}

CComplex operator -( CComplex & another )
{
return CComplex( real- another.real, image - another.image );
}

CComplex operator *( CComplex & another )
{
CComplex prod;
//prod = *this;

prod.real = real*another.real - image*another.im