4.C++运算符重载

C++运算符重载

  • 成员函数重载
    成员函数重载本质
    Person p3 = p1.operator+(p2)
    image.png
#include

using namespace std;
class Person
{
public:
    int m_A;
    int m_B;/*
    Person operator+(Person &p)
    {
        this->m_A += p.m_A;
        this->m_B += p.m_B;
        return *this;
    }
    */
};

Person operator+(Person &p1, Person &p2)
{
    p1.m_A +=  p2.m_A;
    p1.m_B +=  p2.m_B;
    return p1;
}
void tets01()
{
    Person p1;
    p1.m_A = 10;
    p1.m_B = 10;
    Person p2;
    p2.m_A = 10;
    p2.m_B = 10;
    //成员函数重载本质
    //Person p3 = p1.operator+(p2)
    //全局函数重载本质
    //Person p3 = operator+(p1, p2)
    Person p3 = p1 + p2;
    cout << "加法运算后的结果: " << p3.m_A << endl;
}

int main()
{
    tets01();
    system("pause");
    return 0;
}
  • 通过全局函数重载
    image.png

    全局函数重载本质
    Person p3 = operator+(p1, p2)
/*
Person operator+(Person &p1, Person &p2)
{
    Person temp;
    temp.m_A = p1.m_A + p2.m_A;
    temp.m_B = p1.m_B + p2.m_B;
    return temp;
}*/

Person operator+(Person &p1, Person &p2)
{
    p1.m_A +=  p2.m_A;
    p1.m_B +=  p2.m_B;
    return p1;
}

总结:内置的数据类型运算符是不能改变的,不要滥用运算符

左移运算符重载-只能运用全局函数实现

利用成员函数实现左移重载.poperator<< (cout)简化版本p << cout
不会利用成员函数重载<<运算符,因为无法实现cout在左侧
void operator<<(Person )

*********************************************
#include

using namespace std;
class Person
{
    //全局函数重载访问私有内容
    friend ostream & operator<<(ostream &cout, Person &p);
public:
    //利用成员函数实现左移重载.poperator<< (cout)简化版本p << cout
    //不会利用成员函数重载<<运算符,因为无法实现cout在左侧
    //void operator<<(Person )
    Person(int m_A, int m_B) :m_A(m_A), m_B(m_B)
    {
        
    }
private:

    int m_A;
    int m_B;
};
ostream & operator<<(ostream &cout, Person &p)//本质 operator << (out, p) 简化 cout << p
{
    cout << "m_A = " << p.m_A << "m_B = " << p.m_B;
    return cout;
}
void test01()
{
    Person p(10,20);
    
    cout << p << endl;
}
int main()
{
    test01();
    system("pause");
    return 0;
}

重载递增++操作

#include
#include
using namespace std;
class MyInteger
{
    friend ostream & operator<<(ostream &out, MyInteger &myint);
public:
    MyInteger()
    {
        m_Num = 0;
    }
    //重载++运算
    MyInteger & operator++()
    {
        this->m_Num++;
        return *this;
    }
    //后置++
    MyInteger operator++(int)   //int代表占位参数,可以用于区分前置和后置递增
    {
        MyInteger temp = *this;
        m_Num++;
        return temp;
    }
private:
    int m_Num;
};
//重载<<运算符
ostream & operator<<(ostream &out, MyInteger &myint)
{
    out << myint.m_Num;
    return out;
}

void test02()
{
    MyInteger myint;

    cout << myint++ << endl;
    cout << myint << endl;
}
int main()
{
    test02();
    system("pause");
    return 0;
}

你可能感兴趣的:(4.C++运算符重载)