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);
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)
{
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)
{
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;
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;
}
这篇只实现了几种简单的复数类,仅供参考。