c++ 复数类

测试而已,不完整。
complex.h

#ifndef _COMPLEX_H
#define _COMPLEX_H
class complex{
    public://构造函数
        complex():_real(0),_imag(0){}
        complex(double real):_real(real),_imag(0){}
        complex(double real,double imag):_real(real),_imag(imag){}

    public://设置和获取实部和虚部的值
        double GetReal() const{return _real;}//获取实部的值
        double GetImag() const{return _imag;}//获取虚部的值
        void   SetReal(double real);  //更改实部的值
        void   SetImag(double imag);  //更改虚部的值
        void   SetVal(double real,double imag); //更改整个复数

    public:     
        friend complex  operator+(const complex &lhs,const complex &rhs);
//      complex&    operator+ (const complex &val);
        complex&    operator* (const complex &val);
        complex&    operator+=(const complex &val);                         
        complex&    operator*=(const complex &val);                           

        friend bool operator==(const complex &lhs,const complex &rhs);
        friend bool operator!=(const complex &lhs,const complex &rhs);

    private:
        double _real;//实部
        double _imag;//虚部

};
#endif

complex.cpp

#include <stdafx.h>
#include "complex.h"

void   complex::SetReal(double real)
{
    _real = real;
}   

void   complex::SetImag(double imag)   
{
    _imag = imag;
}  

void   complex::SetVal(double real,double imag)
{
    _real = real;
    _imag = imag;
}

/// 
complex operator+ (const complex &lhs,const complex &rhs)
{
     return complex(lhs._real+rhs._real,lhs._imag+rhs._imag);  
}

complex&    complex::operator* (const complex &val)
{
    complex temp(*this);  
    temp *= val;  
    return temp;
}

complex&    complex::operator+=(const complex &val)
{
    _real += val._real;
    _imag += val._imag;
    return *this;
}

complex&    complex::operator*=(const complex &val)
{
    double retReal = _real;
    double retImag = _imag;
    _real = retReal*val._real - retImag*val._imag;
    _imag = retReal*val._imag + retImag*val._real;
    return *this;
}

bool operator==(const complex &lhs,const complex &rhs)
{
    return (lhs._real == rhs._real) && (lhs._imag == rhs._imag);
}

bool operator!=(const complex &lhs,const complex &rhs)
{
    return !(lhs==rhs);
}


标准库提供的复数类是一个模板。

template<class T>
class complex{
    public:
        complex(T re,T im);
        //......
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值