实验1

#ifndef COMPLEX_HPP
#define COMPLEX_HPP
#include <iostream>
#include <iomanip>
#include <string>
#include <math.h>
using namespace std;
class Complex
{
public:
    Complex(){
    };
    Complex(double r,double i);
    Complex(double r);
    Complex(const Complex &c);
    ~Complex(){};
    double get_real() const;
    double get_imag() const;
    void show() const;
    void add(const Complex &c);
    friend Complex add(const Complex &c1,const Complex &c2);
    friend bool is_equal(const Complex &c1,const Complex &c2);
    friend double abs(const Complex &c);
private:
    double real;
    double imag;
};
Complex::Complex(double r,double i):real(r),imag(i){}
Complex::Complex(double r):real(r),imag(0.0){}
Complex::Complex(const Complex &c):real(c.real),imag(c.imag){}
double Complex::get_real() const{
    return real;
}
double Complex::get_imag() const{
    return imag;
}
void Complex::show() const{
    if(imag>0)
        cout<<real<<"+"<<imag<<"i";
        else if(imag==0)
        cout<<real;
    else
        cout<<real<<imag<<"i";
}
void Complex::add(const Complex &c){
    real+=c.real;
    imag+=c.imag;
}
Complex add(const Complex &c1,const Complex &c2){
    Complex c;
    c.imag=c1.imag+c2.imag;
    c.real=c1.real+c2.real;
    return c;
}
bool is_equal(const Complex &c1,const Complex &c2){
    if (c1.imag==c2.imag)
        return true;
    else
        return false;
}
double abs(const Complex &c){
    return sqrt(c.imag*c.imag+c.real*c.real);
}
#endif
#include "Complex.hpp"
#include <iostream>

int main()
{
    using namespace std;

    Complex c1(1, -1);
    const Complex c2(1.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;
}

实验1

 

 

上一篇:实验5 模板类与多态


下一篇:浅拷贝的应用(element-ui中的表格【table】与对话框【Dialog】的综合)