跳到正文

个人记录

手打复数模板

小菜鸟约 4 分钟
原文
文章信息与版本

文章信息

发布
2018年6月14日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

花了一上午写的复数模板,支持的功能还是很多的2333

C++
template<class T>
class complex
{
    private:
    T r,i;
    public:
    complex(const T& x=0,const T& y=0):r(x),i(y){}
    T& real()const{return r;}
    T& imag()const{return i;}
    static T abs(const complex& x){return sqrt(x.r*x.r+x.i*x.i);}
    static T arg(const complex& x){return atan2(x.i,x.r);}
    static complex polar(const T& _r,const T& Theta){return complex(_r*cos(Theta),_r*sin(Theta));}
    complex conj()const{return complex(r,-i);}
    complex operator+=(const T& b){r+=b;return *this;}
    complex operator+=(const complex& b){r+=b.r;i+=b.i;return *this;}
    template<class U>
    complex operator+(const U& b)const
    {
        complex c=*this;
        c+=b;
        return c;
    }
    friend complex operator+(const T& a,const complex& b){return b+a;}
    complex operator-=(const T& b){r-=b;return *this;}
    complex operator-=(const complex& b){r-=b.r;i-=b.i;return *this;}
    template<class U>
    complex operator-(const U& b)const
    {
        complex c=*this;
        c-=b;
        return c;
    }
    friend complex operator-(const T& a,const complex& b){return complex(a)-b;}
    complex operator*=(const T& b){r*=b,i*=b;return *this;}
    complex operator*=(const complex& b){complex c=*this;r=b.r*c.r-b.i*c.i;i=b.r*c.i+b.i*c.r;return *this;}
    template<class U>
    complex operator*(const U& b)const
    {
        complex c=*this;
        c*=b;
        return c;
    }
    friend complex operator*(const T& a,const complex& b){return b*a;}
    complex operator/=(const T& b){r/=b,i/=b;return *this;}
    complex operator/=(const complex& b){complex c=b.conj();*this/=(b*c).r;*this*=c;return *this;}
    template<class U>
    complex operator/(const U& b)const
    {
        complex c=*this;
        c/=b;
        return c;
    }
    friend complex operator/(const T& a,const complex& b){return complex(a)/b;}
};
原文
存档评论1 条抓取于