实验一 类与对象 task3 Complex类

2021/10/23 23:11:38

本文主要是介绍实验一 类与对象 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;
}

 



这篇关于实验一 类与对象 task3 Complex类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程