C++学习历程(三)运算符重载

 
 

1.什么是运算符重载?

答:给运算符重新赋予新的含义,实现所定义的功能。  本质:重载即函数

注意:运算符重载后,其原本的含义仍在,仍可以使用。

#include <iostream>

using namespace std;

class Complex
{
    friend ostream &operator <<(ostream &out,const Complex &c);
    int m_a;
    int m_b;
public:
    Complex();
    Complex(int a,int b);
    int GetA();
    int GetB();
    Complex &operator +(Complex &c);
    Complex operator ++(int);           //后置++,用占位参数int来区别
    Complex &operator ++();             //前置++,不需要占位参数
    Complex &operator =(const Complex &c);
    bool operator ==(const Complex &c);
    bool operator !=(const Complex &c);
    //ostream &operator <<(ostream &out);   错的,不能用成员函数
    //friend Complex operator +(Complex c1,Complex c2);

};

Complex::Complex()
{
    m_a = 0;
    m_b = 0;
}

Complex::Complex(int a,int b)
{
    m_a = a;
    m_b = b;
}

int Complex::GetA()
{
    return m_a;
}

int Complex::GetB()
{
    return m_b;
}
/*
Complex operator +(Complex c1,Complex c2)
{
    Complex ret;
    ret.m_a = c1.m_a + c2.m_a;
    ret.m_b = c1.m_b + c2.m_b;

    return ret;             //返回的是ret中的值,而不是地址空间
}*/

Complex &Complex::operator +(Complex &c)
{
    this -> m_a = m_a + c.m_a;
    this -> m_b = this -> m_b + c.m_b;

    return *this;
}

/*ostream & Complex::operator <<(ostream &out)
{
    out << this -> m_a << " + " << this -> m_b << "i";
    return out;
}
*/


Complex Complex::operator ++(int)
{
    Complex temp = *this;
    m_a ++;
    m_b ++;
    return temp;
}

Complex &Complex::operator ++()
{
    m_a++;
    m_b++;
    return *this;
}

ostream &operator <<(ostream &out,const Complex &c)
{
    out << c.m_a << "+" << c.m_b << "i";
    return out;
}

Complex &Complex::operator =(const Complex &c)
{
   m_a = c.m_a;
   m_b = c.m_b;
   return *this;
}

bool Complex::operator ==(const Complex &c)
{
    if(m_a == c.m_a && m_b == c.m_b)
        return true;
    else 
        return false;
}

bool Complex::operator !=(const Complex &c)
{
    return (m_a != c.m_a || m_b != c.m_b);
}

int main(int argc, char **argv)
{
    Complex c1(1,2);
    Complex c2(2,3);

    Complex c3;

    //c3 = operator +(c1,c2);
    //c3 = c1 + c2;
    //c3 = c1.operator +(c2);
    c3 = c1 + c2;

    c3 = c2;

    if(c3 == c1)
    {
        cout << "equal" << endl;
    }
    else 
    {
        cout << "not equal" << endl;
    }

    if(c3 != c2)
    {
        cout << "not equal " << endl;
    }
    else 
    {
        cout << "equal" << endl;
    }
    cout << c3++ << endl;
    cout << ++c3 << endl;
    cout << c2 << endl;
    //cout << c3.GetA() << " + " << c3.GetB() << "i" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhanganliu/article/details/79807728