运算符+-*/的重载代码

来源:互联网 发布:苍云成男捏脸数据 编辑:程序博客网 时间:2024/06/10 21:17
#include<iostream>
using namespace std;


class Complex
{
public:
Complex(double real = 0,double imag = 0);
Complex operator +(const Complex & c2);
Complex operator -(const Complex & c2);
Complex operator *(const Complex & c2);
Complex operator /(const Complex & c2);
void display(){cout << "real:" << m_real << ",imag" << m_imag << endl;}
private:
double m_real;
double m_imag;
};
Complex::Complex(double real,double imag)
{
m_real = real;
m_imag = imag;
}
Complex Complex::operator +(const Complex & c2)
{
Complex result;
result.m_real = m_real + c2.m_real ;
result.m_imag = m_imag + c2.m_imag;
return result;
}
Complex Complex::operator -(const Complex & c2)
{
Complex result;
result.m_real = m_real - c2.m_real ;
result.m_imag = m_imag - c2.m_imag;
return result;
}
Complex Complex::operator *(const Complex & c2)
{
Complex result;
result.m_real = m_real * c2.m_real - m_imag * c2.m_imag;
result.m_imag = m_real * c2.m_imag + m_imag * c2.m_real;
return result;
}
Complex Complex::operator /(const Complex & c2)
{
Complex result;
double d = c2.m_imag * c2.m_imag + c2.m_real * c2.m_real;
result.m_real = (m_real * c2.m_real + m_imag * c2.m_imag)/d ;
result.m_imag = (-m_real * c2.m_imag + m_imag * c2.m_real)/d;
return result;
}
int main()
{
Complex c1(3,4),c2(4,7);
Complex c3 = c1 + c2 * c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
Complex c6 = c1 / c2;
c3.display();
c4.display();
c5.display();
c6.display();


system("pause");
return 0;
}
原创粉丝点击