c++实验报告——复数类Complex

本文档提供了一个C++实现的复数类`Complex`,包含构造函数、获取实部和虚部的成员函数、显示复数、复数加法、比较和取模运算等功能。同时,`Complex`类还定义了友元函数以实现复数相加、比较和取模。通过示例代码展示了如何使用这些接口进行复数操作。
摘要由CSDN通过智能技术生成
不使用 C++ 标准库,自行设计并实现一个复数类 Complex ,使其满足如下要求:
数据成员
用来表示复数的实部 real 和虚部 imag ,实部、虚部,均为小数形式。
函数成员
构造函数
支持以下方式定义复数对象:
成员函数
get_real() 返回复数实部
get_imag() 返回复数虚部
show() 用于输出复数。要求以 3 + 4i 3 - 4i 这样的形式输出
add() 用于把一个复数加到自身,比如 c1.add(c2) ,相当于 c1 += c2
友元函数
add() 用于实现两个复数相加,返回复数。比如 c3 = add(c1, c2) ;
is_equal() 用于判断两个复数是否相等,返回 true/false 。比如 is_equal(c1, c2)
abs() 用于对复数进行取模运算
将类 Complex 的定义及友元函数实现,单独保存在文件 Complex.hpp 中。
使用 task3.cpp 中的代码,测试类 Complex 的各项接口是否正确。
#include "Complex.hpp"
#include <iostream>

int main()
{
    using namespace std;

    Complex c1(11, -4);
    const Complex c2(4.5);
    Complex c3(c1);

    cout << "c1 = ";
    c1.show();
    cout << endl;

    cout << "c2 = ";
    c2.show();
    cout << endl;
    cout << "c2.imag = " << c2.get_imag() << endl;

    cout << "c3 = ";
    c3.show();
    cout << endl;

    cout << "abs(c1) = ";
    cout << abs(c1) << endl;

    cout << boolalpha;
    cout << "c1 == c3 : " << is_equal(c1, c3) << endl;
    cout << "c1 == c2 : " << is_equal(c1, c2) << endl;

    Complex c4;
    c4 = add(c1, c2);
    cout << "c4 = c1 + c2 = ";
    c4.show();
    cout << endl;

    c1.add(c2);
    cout << "c1 += c2, " << "c1 = ";
    c1.show();
    cout << endl;

    return 0;
}
#include<iostream>
#include<cmath>
using namespace std;

class Complex
{
public:
    Complex(double a = 0,double b = 0):real{a},imag{b} {};
    Complex(const Complex &c1);
    ~Complex() = default;

    double get_real() const {return real;}
    double get_imag() const {return imag;}
    void show() const;
    void add(Complex const &c1);
    

    friend Complex add(Complex const&c1,Complex const&c2);
    friend bool is_equal(Complex const&c1,Complex const&c2);
    friend double abs(Complex const&c1); 
private:
    double real;
    double imag;
};

Complex::Complex(const Complex &c1)
{
    real = c1.real;
    imag = c1.imag;
}

void Complex::show() const
{
    if(imag == 0)
        cout << real ;
    else if(imag < 0)
        cout << real <<" - "<< abs(imag) << "i" ;
    else
        cout << real <<" + "<< imag << "i" ;
}

void Complex::add(Complex const&c1)
{
    real += c1.real;
    imag += c1.imag;
}


Complex add(Complex const&c1,Complex const&c2)
{
    Complex c3;
    c3.real = c1.real + c2.real;
    c3.imag = c1.imag + c2.imag;
    return c3;
}

bool is_equal(Complex const&c1,Complex const&c2)
{
    if(c1.real == c2.real&&c1.imag ==c2.imag)
        return true;
    return false;
}

double abs(Complex const&c1)
{
    return sqrt(c1.real*c1.real + c1.imag*c1.imag);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值