c++复数类Complex的编写

时间:2022-03-11 19:48:37

c++复数类Complex的编写。

复数:由实部和虚部组成。

主要实现几个运算符的重载:=/==/+/-/+=/-+/前置++/前置–/后置++/后置–

主要实现代码如下:

头文件Complex.h 函数声明和类定义

#include<iostream>
#pragma once

class Complex
{
public:
Complex(double real=0.0,double image=0.0);//构造
~Complex();//析构
Complex(Complex& c1);//拷贝构造

//运算符重载
Complex &operator=(const Complex &d); //赋值函数
bool operator==(const Complex &d);//判断相等
Complex operator+(const Complex &d);//两个复数相加
Complex &operator+=(const Complex &d);//复数+=d
Complex operator-(const Complex &d);//两复数相减
Complex &operator-=(const Complex &d);//复数-=
Complex operator++(); //前置++
Complex operator++(int);//后置++
Complex operator--();//前置--
Complex operator--(int);//后置--
void Display();//显示复数的实部和虚部
private:
double _real;
double _image;
};

源文件 Complex.cpp 类的成员函数实现:

#include"Complex.h"

//构造函数
Complex::Complex(double real,double image)
{
_real=real;
_image=image;
}

//拷贝构造函数
Complex::Complex(Complex & c1)
:_real(c1._real),
_image(c1._image)
{

}
//析构函数
Complex::~Complex()
{

}

Complex& Complex::operator=(const Complex &d)//赋值运算符的重载
{
this->_real=d._real;
this->_image=d._image;
return *this;
}

bool Complex::operator==(const Complex &d)//判断相等
{
return this->_real ==d._real&&this->_image==d._image;
}

Complex Complex ::operator+(const Complex &d)//两个复数相加
{
Complex tmp;
tmp._image=this->_image+d._image;
tmp._real=this->_real+d._real;
return tmp;
}

Complex& Complex::operator+=(const Complex &d)//复数+=d
{
this->_image+=d._image;
this->_real+=d._real;
return *this;
}

Complex Complex::operator-(const Complex &d)//两个复数相减
{
Complex tmp;
tmp._image=this->_image-d._image;
tmp._real=this->_real-d._real;
return tmp;
}

Complex& Complex::operator-=(const Complex &d)//复数-=d
{
this->_image-=d._image;
this->_real-=d._real;
return *this;
}

Complex Complex::operator++()//前置++
{
this->_real++;
this->_image++;
return *this;
}

Complex Complex::operator++(int)//后置++
{
Complex tmp;
tmp=*this;
this->_image++;
this->_real++;
return tmp;
}

Complex Complex::operator--()//前置--
{
this->_image--;
this->_real--;
return *this;
}

Complex Complex::operator--(int)//后置--
{
Complex tmp=*this;
this->_image--;
this->_real--;
return tmp;
}

void Complex::Display()//输出复数的实部和虚部
{
std::cout<<"real:"<<_real<<std::endl;
std::cout<<"image:"<<_image<<std::endl;
}

测试部分在text.cpp中

#include"Complex.h"
#include<stdlib.h>
#include<iostream>
using namespace std;


void Test1() //+= -= + - 测试
{
Complex c1(1.0,2.0), c2(2.0,1.0);
Complex c3=c1 -= c2;
//Complex c3=c1 += c2;
//Complex c3 = c1 + c2;
//Complex c3=c1 - c2;
c1.Display();
c3.Display();
}
void Test2() // ++测试
{
Complex c1(1.0, 5.0);
Complex c2=c1++;
Complex c3 = ++c1;
c1.Display();
c2.Display();
c3.Display();
}


void Test3()
{
Complex c1(1.0, 5.0);
Complex c2 = c1--;
Complex c3 = --c1;
c1.Display();
c2.Display();
c3.Display();
}
int main()
{
Test3();
system("pause");
return 0;
}

这篇只实现了几种简单的复数类,仅供参考。