今天,我来学习将复数的加减乘除以及比较运算,编写一个复数类,方便计算复数之间的运算。具体用的方法就是之前写过的操作符重载的概念来实现(操作符重载的概念学习)。
那么为了显得清晰,今天写的程序运用模块化的思想:

Complex.h为:

#ifndef _COMPLEX_H_
#define _COMPLEX_H_

class Complex
{
    double a;
    double b;
public:
    Complex(double a = 0, double b = 0);
    double getA();
    double getB();
    double getModulus();
    
    Complex operator + (const Complex& c);
    Complex operator - (const Complex& c);
    Complex operator * (const Complex& c);
    Complex operator / (const Complex& c);
    
    bool operator == (const Complex& c);
    bool operator != (const Complex& c);
    
    Complex& operator = (const Complex& c);
};

#endif

Complex.cpp为:

#include "Complex.h"
#include "math.h"

Complex::Complex(double a, double b)
{
    this->a = a;
    this->b = b;
}

double Complex::getA()
{
    return a;
}

double Complex::getB()
{
    return b;
}

double Complex::getModulus()
{
    return sqrt(a * a + b * b);
}

Complex Complex::operator + (const Complex& c)
{
    double na = a + c.a;
    double nb = b + c.b;
    Complex ret(na, nb);
    
    return ret;
}

Complex Complex::operator - (const Complex& c)
{
    double na = a - c.a;
    double nb = b - c.b;
    Complex ret(na, nb);
    
    return ret;
}

Complex Complex::operator * (const Complex& c)
{
    double na = a * c.a - b * c.b;
    double nb = a * c.b + b * c.a;
    Complex ret(na, nb);
    
    return ret;
}

Complex Complex::operator / (const Complex& c)
{
    double cm = c.a * c.a + c.b * c.b;
    double na = (a * c.a + b * c.b) / cm;
    double nb = (b * c.a - a * c.b) / cm;
    Complex ret(na, nb);
    
    return ret;
}
    
bool Complex::operator == (const Complex& c)
{
    return (a == c.a) && (b == c.b);
}

bool Complex::operator != (const Complex& c)
{
    return !(*this == c);
}
    
Complex& Complex::operator = (const Complex& c)
{
    if( this != &c )
    {
        a = c.a;
        b = c.b;
    }
    
    return *this;
}

main.cpp为:

#include <stdio.h>
#include "Complex.h"

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 6);
    Complex c3 = c2 - c1;
    Complex c4 = c1 * c3;
    Complex c5 = c2 / c1;
    
    printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB());
    printf("c4.a = %f, c4.b = %f\n", c4.getA(), c4.getB());
    printf("c5.a = %f, c5.b = %f\n", c5.getA(), c5.getB());
    
    Complex c6(2, 4);
    
    printf("c3 == c6 : %d\n", c3 == c6);
    printf("c3 != c4 : %d\n", c3 != c4);
    
    (c3 = c2) = c1;
    
    printf("c1.a = %f, c1.b = %f\n", c1.getA(), c1.getB());
    printf("c2.a = %f, c2.b = %f\n", c2.getA(), c2.getB());
    printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB());
    
    return 0;
}

以上模块代码实现了,复数的四则运算法则以及比较的法则,运用了操作符重载的概念。代码都可以通过链接直接下载得到源代码下载链接码云平台

注意事项:

  1. C++赋值操作符(=)只能重载为成员函数
  2. 操作符重载不能改变原操作符的优先级
  3. 操作符重载不能改变原操作数的个数
  4. 操作符重载不能改变原操作符的语义

总结:

  • 复数的概念可以通过自定义类实现
  • 复数中的运算操作可以通过操作符重载实现
  • 赋值操作符只能通过厂原函数实现
  • 操作符重载的本质为函数定义

想获得各种学习资源以及交流学习的加我(有我博客中写的代码的原稿):
qq:1126137994
微信:liu1126137994
可以共同交流关于嵌入式,操作系统,C++语言,C语言,数据结构等技术问题。