C++入门笔记<实现复数类>

来源:互联网 发布:剑灵召唤师捏脸数据图 编辑:程序博客网 时间:2024/06/03 17:38

最近在学习C++,刚好看到了重载,之前写过FFT,当时还不会重载运算符,都是用函数实现的。今天学了一下,就写了一个复数的类,原理很简单,功能也比较简单,就是实现了复数的基本操作。包括:加减乘除、求共轭、求模、求相角。初始化以后使用起来和其他变量一样。下面是main中的片段。

  ccomplex a(1,1),b(1,1);    std::cout<<"a="<<a.Real()<<"+"<<a.Img()<<"*i"<<std::endl;    std::cout<<"b="<<b.Real()<<"+"<<b.Img()<<"*i"<<std::endl;    std::cout<<"a+b="<<(a+b).Real()<<"+"<<(a+b).Img()<<"*i"<<std::endl;    std::cout<<"a-b="<<(a-b).Real()<<"+"<<(a-b).Img()<<"*i"<<std::endl;    std::cout<<"a*b="<<(a*b).Real()<<"+"<<(a*b).Img()<<"*i"<<std::endl;    std::cout<<"a/b="<<(a/b).Real()<<"+"<<(a/b).Img()<<"*i"<<std::endl;    std::cout<<"~b="<<(~b).Real()<<"+"<<(~b).Img()<<"*i"<<std::endl;    std::cout<<"|b|="<<b.Abs()<<std::endl;    std::cout<<"angle(b)="<<b.Angle()<<std::endl;   


</pre><pre name="code" class="cpp">//complex.cpp#include"complex.h"#include<cmath>ccomplex::ccomplex(double real,double image){    this->image=image;    this->real=real;}ccomplex::~ccomplex(){}double ccomplex::Abs(){    return sqrt(this->image*this->image+this->real*this->real);}double ccomplex::Angle(){    double abs=this->Abs();    if(!abs) return 0;    return asin(this->image/abs);}double ccomplex::Real(){    return this->real;}double ccomplex::Img(){    return this->image;}ccomplex ccomplex::operator*(const ccomplex &a)const{    ccomplex b(this->real*a.real-this->image*a.image,this->real*a.image+this->image*a.real);    return b;}ccomplex ccomplex::operator+(const ccomplex &a)const{    ccomplex b(this->real+a.real,this->image+a.image);    return b;}ccomplex ccomplex::operator-(const ccomplex &a)const{    ccomplex b(this->real-a.real,this->image-a.image);    return b;}ccomplex ccomplex::operator/(const ccomplex &a)const{    ccomplex b((this->real*a.real+a.image*this->image)/(a.image*a.image+a.real*a.real),(this->image*a.real-this->real*a.image)/(a.image*a.image+a.real*a.real));    return b;}ccomplex ccomplex::operator~()const{    ccomplex b(this->real,-this->image);    return b;}

//complex.h#ifndef COMPLEX_H_#define COMPLEX_H_class ccomplex{private:    double image;    double real;public:    ccomplex(double image=0,double real=0);    ~ccomplex();    ccomplex operator+(const ccomplex &a)const;    ccomplex operator-(const ccomplex &a)const;    ccomplex operator*(const ccomplex &a)const;    ccomplex operator/(const ccomplex &a)const;    ccomplex operator~()const;    double Img();    double Real();    double Abs();    double Angle();};#endif // COMPLEX_H_

0 0
原创粉丝点击