实验一 类与对象

#ifndef COMPLEX_HPP
#define COMPLEX_HPP 
#include<iostream>
#include<cmath>
using namespace std;
class Complex
{
private:
    double real,image;
public:
    Complex(const double x,const double y):real(x),image(y){};
    Complex(){}
    Complex(const double x):real(x),image(0){}
    Complex(const Complex &c):real(c.real),image(c.image){}
    double get_real()const{return real;}
    double get_image()const{return image;}
    void show()const;
    void add(Complex c){real+=c.real;image+=c.image;}
    ~Complex()=default;
    friend Complex add(const Complex c1,const Complex c2);
    friend bool is_equal(const Complex c1,const Complex c2);
    friend double abs(const Complex c1);
};
void Complex:: show()const
{
    if(image>0)
    cout<<real<<"+"<<image<<"i"<<endl;
    else if(image<0)
    cout<<real<<image<<"i"<<endl;
    else
    cout<<real<<endl;
}
Complex add(const Complex c1,const Complex c2)
{
    Complex c3;
    c3.real=c1.real+c2.real;
    c3.image=c1.image+c2.image;
    return c3;
}
bool is_equal(const Complex c1,const Complex c2)
{
    if(c1.real==c2.real&&c1.image==c2.image)
    return true;
    else 
    return false;
}
double abs(const Complex c1)
{
    return sqrt(c1.real*c1.real+c1.image*c1.image);
}
#endif
#include "Complex.hpp"
#include <iostream>
int main()
{
    using namespace std;
    Complex c1(5, -12);
    const Complex c2(2.5);
    Complex c3(c1);
    cout << "c1 = ";
    c1.show();
    cout << endl;
    cout << "c2 = ";
    c2.show();
    cout << endl;
    cout << "c2.imag = " << c2.get_image() << 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;
}

实验一 类与对象

注意const类型的使用 

上一篇:重学C++(二)


下一篇:task3