c++: 复数类

本文介绍了一个C++复数类的实现,包括加、减、乘、除等基本运算的重载,以及输入输出运算符的重载。通过实例展示了如何使用该复数类进行复数运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++: 复数类

#include<iostream>
using namespace std;

class complex
{
private:
   double real;
   double imaginary ;
public:
    complex():real(0),imaginary(0){}
    complex(double x,double y):real(x),imaginary(y){}
    void operator = (const complex&c){
        real=c.real;
        imaginary=c.imaginary;
    }
    ~complex(){}
    complex operator- () {
        return complex(-real,-imaginary);
    }
    complex operator+(const complex&c){
        complex com;
        com.real=real+c.real;
        com.imaginary=imaginary+c.imaginary;
        return com;
    }// 定义复数加法
    complex operator-(const complex&c){
        complex com;
        com.real = real - c.real;
        com.imaginary = imaginary - c.imaginary;
        return com;
    }//定义复数减法
    complex operator*(const complex&c){
        complex com ;
        com.real = real*c.real - imaginary*c.imaginary;
        com.imaginary = real*c.imaginary + imaginary*c.real;
        return com;
    }// 定义复数除法
    complex operator/(const complex&c){
        complex com;
        double denominator = c.real*c.real + c.imaginary*c.imaginary;
        com.real = (real*c.real + imaginary*c.imaginary)/denominator;
        com.imaginary = (imaginary*c.real-real*c.imaginary)/denominator;
        return com;
    }

    /*习惯上人们是使用 cin>> 和 cout<< 的,得使用友元函数来重载运算符,
    如果使用成员函数来重载会出现 d1<<cout; 这种不自然的代码*/
    friend ostream &operator<<( ostream &output, const complex &c ){ 
         output <<"( "<< c.real<<" ," <<c.imaginary<<" i )";
         return output;            
    }//输出运算符重载
    friend istream &operator>>( istream  &input, complex &c ){ 
         input >> c.real >> c.imaginary;
         return input;            
    }//输入运算符重载
};

int main(){
    complex a(4,6),b(2,-1);
    cout<<a<<" + "<<b<<" = "<<a+b<<endl;
    cout<<a<<" - "<<b<<" = "<<a-b<<endl;
    cout<<a<<" * "<<b<<" = "<<a*b<<endl;
    cout<<a<<" / "<<b<<" = "<<a/b<<endl;
    return 0;
}

输出

( 4 ,6 i ) + ( 2 ,-1 i ) = ( 6 ,5 i )
( 4 ,6 i ) - ( 2 ,-1 i ) = ( 2 ,7 i )
( 4 ,6 i ) * ( 2 ,-1 i ) = ( 14 ,8 i )
( 4 ,6 i ) / ( 2 ,-1 i ) = ( 0.4 ,3.2 i )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值