美文网首页
C语言关键字

C语言关键字

作者: 踩在浪花上00 | 来源:发表于2016-10-19 15:01 被阅读0次

    complex.h

    #ifndef COMPLEX_H

    #define COMPLEX_H

    #include using namespace std;

    class Complex

    {

    public:

    //explicit :防止隐士类型转换

    //explicit Complex(float real = 0, float vir = 0);

    Complex(float real = 0, float vir = 0);

    ~Complex();

    //类型转换函数无需写返回值类型,但是函数定义中必须要有返回值

    operator int();

    operator float();

    void value();

    friend Complex operator +(Complex &c1, Complex &c2);

    friend Complex operator -(Complex &c1, Complex &c2);

    private:

    float m_fReal;

    float m_fVir;

    };

    Complex operator +(Complex &c1, Complex &c2);

    Complex operator -(Complex &c1, Complex &c2);

    complex.cpp

    de "complex.h"

    Complex::Complex(float real, float vir)

    {

    m_fReal = real;

    m_fVir = vir;

    }

    Complex::~Complex()

    {}

    Complex Complex::operator+(int data)

    {

    Complex com;

    com.m_fReal = m_fReal + data;

    com.m_fVir = m_fVir;

    cout << "Complex::operator+(int data)" << endl;

    return com;

    }

    Complex Complex::operator+(float data)

    {

    Complex com;

    com.m_fReal = m_fReal + data;

    com.m_fVir = m_fVir;

    cout << "Complex::operator+(float data)" << endl;

    return com;

    }

    Complex::operator float()

    {

    cout << "operator float()" << endl;

    return (m_fReal + m_fVir) * 0.05;

    }

    Complex::operator int()

    {

    cout << "operator int()" << endl;

    return m_fReal;

    }

    void Complex::value()

    {

    cout << '(' << m_fReal << ")+(" << m_fVir

    << ")i" << endl;

    }

    Complex operator +(Complex &c1

    , Complex &c2)

    {

    Complex c;

    c.m_fReal = c1.m_fReal + c2.m_fReal;

    c.m_fVir = c1.m_fVir + c2.m_fVir;

    cout << "operator+" << endl;

    return c;

    }

    Complex operator -(Complex &c1

    , Complex &c2)

    {

    Complex c;

    c.m_fReal = c1.m_fReal - c2.m_fReal;

    c.m_fVir = c1.m_fVir - c2.m_fVir;

    cout << "operator-" << endl;

    return c;

    }

    main.cpp

    nclude "complex.h"

    void fun(Complex com)

    {

    com.value();

    }

    int main()

    {

    //int 转换成Complex:隐士类型转换

    //fun(23);

    Complex com(3, 7);

    com.value();

    Complex com2(4, 9);

    com2.value();

    Complex com3 = com + com2;

    com3.value();

    Complex com4 = com - com2;

    com4.value();

    return 0;

    }

    #endif // COMPLEX_H

    相关文章

      网友评论

          本文标题:C语言关键字

          本文链接:https://www.haomeiwen.com/subject/mpsxuttx.html