其他分享
首页 > 其他分享> > 实验一 类与对象 task3 Complex类

实验一 类与对象 task3 Complex类

作者:互联网

#include<iostream>
#include<cmath>
using namespace std;

class Complex {
private:
    double real;
    double imag;
public:
    Complex(double x = 0, double y = 0) :real(x), imag(y) {}
    Complex(Complex& p);
        double get_real() const;
        double get_imag() const;
        void show()const;
        void add(const Complex& p);
        friend Complex add(const Complex& a, const Complex& b);
        friend bool is_equal(const Complex& a, const Complex& b);
        friend double abs(Complex& a);
};

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

double Complex::get_real()const {
    return real;
}

double Complex::get_imag()const {
    return imag;
}

void Complex::show()const {
    cout << real;
    if (imag < 0)
        cout << imag << 'i';
    else if (imag > 0)
        cout << ' + ' << imag << 'i' ;
}

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

Complex add(const Complex& a, const Complex& b) {
    Complex c;
    c.real = a.real+ b.real;
    c.imag = a.imag+ b.imag;
    return c;
}

bool is_equal(const Complex& a, const Complex& b) {
    if (a.real == b.real && a.imag == b.imag)
        return true;
    else return false;
}

double abs(Complex& a) {
    return sqrt(a.real * a.real + a.imag * a.imag);
}
#include "Complex.hpp"
#include <iostream>

#include<cmath>

int main()
{
    using namespace std;

    Complex c1(3, -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;
}

 

标签:real,task3,const,double,imag,Complex,实验,include
来源: https://www.cnblogs.com/Hershel-Hjh/p/15449854.html