c++ 学习 之 运算符重载

前言

运算符重载的概念:
对已有的运算符重新进行定义,赋予其另外一种功能,以适应不同的数据类型

加号运算符重载

作用:定义两个自定义的数据类型相加的运算

正常情况下,如果想要实现类中两个int 类型的相加,可以参考下面的代码

#define CRT_SECURE_NO_WARNINGS
#include
using namespace std;

class Person
{
public:
    Person(int x, int y)
    {
        m_A = x;
        m_B = y;
    }

    // 修改为返回引用
    Person& add(const Person& p)
    {
        m_A += p.m_A;
        m_B += p.m_B;
        return *this;
    }

    void print()
    {
        cout << "m_A: " << m_A << endl;
        cout << "m_B: " << m_B << endl;
    }
private:
    int m_A;
    int m_B;
};

int main()
{
    Person A(1, 1);
    Person B(2, 2);

    // 使用赋值操作符初始化 c
    Person c = A.add(B);
    c.print();
    return 0;
}

但是上面的代码的话A 和 c 共同使用同一个地址

看看下面的运算符重载

#define CRT_SECURE_NO_WARNINGS
#include
using namespace std;

class Person
{
public:
   
    void print()
    {
        cout << "m_A: " << m_A << endl;
        cout << "m_B: " << m_B << endl;
    }

    int m_A;
    int m_B;
};

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

int main()
{
    Person A;
    A.m_A = 1;
    A.m_B = 1;

    Person B;
    B.m_A = 2;
    B.m_B = 2;

   // Person C = A + B;   这种方式和下面的是等价的
    Person C = operator+(A, B);
    C.print();
    return 0;
}

下面展示成员函数来实现运算符重载

#define CRT_SECURE_NO_WARNINGS
#include
using namespace std;

class Person
{
public:
   
    Person operator+(Person& p1)
    {
        Person tmp;
        tmp.m_A = p1.m_A + this->m_A;
        tmp.m_B = p1.m_B + this->m_B;
        return tmp;

    }
    void print()
    {
        cout << "m_A: " << m_A << endl;
        cout << "m_B: " << m_B << endl;
    }

    int m_A;
    int m_B;
};



int main()
{
    Person A;
    A.m_A = 1;
    A.m_B = 1;

    Person B;
    B.m_A = 2;
    B.m_B = 2;

    Person C = A + B;  // 这种方式和下面的是等价的
    //Person C = A.operator+(B);
    C.print();
    return 0;
}

运算符重载 ,也可以实现 类 与 整形的结合

#define CRT_SECURE_NO_WARNINGS
#include
using namespace std;

class Person
{
public:

    void print()
    {
        cout << "m_A: " << m_A << endl;
        cout << "m_B: " << m_B << endl;
    }

    int m_A;
    int m_B;
};

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

}

// 下面写一个函数重载
Person operator+(Person& p1, int num)
{
    Person tmp;
    tmp.m_A = p1.m_A + num;
    tmp.m_B = p1.m_B + num;
    return tmp;
}

int main()
{
    Person A;
    A.m_A = 1;
    A.m_B = 1;

    Person B;
    B.m_A = 2;
    B.m_B = 2;

    // Person C = A + B;   这种方式和下面的是等价的
    //Person C = operator+(A, B);
    //C.print();
    Person D = A + 10;
    D.print();

    return 0;
}

你可能感兴趣的:(c++,c++,学习,开发语言)