C++基础学习--运算符重载

C++运算符的重载

C++实现运算符的重载其实可以看做是函数的重载,既然可以看做是函数的重载就课又分为成员函数与友元函数

成员函数重载

使用成员函数方式的重载,默认第一个参数会传入this指针

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <queue>
#include "main.h"
using namespace std;

class Compare {
public:
    Compare() = default;
    Compare(int age, int high):age(age),high(high){};
    ~Compare() = default;
    void display()
    {
        printf("age = %d, high = %d\n", age, high);
    }
    Compare operator+(Compare& compare); // 成员函数:重载运算符
private:
    int age;
    int high;
};

Compare Compare::operator+(Compare& com)
{
    Compare temp;
    temp.age = this->age + com.age;
    temp.high = this->high + com.high;
    return temp;
}

int main()
{
    Compare comp1(10, 186);
    Compare comp2(15, 190);
    // 利用成员函数:重载运算符
    Compare result = comp1 + comp2;
    result.display();
    return 0;
}

友元函数重载

使用友元函数重载,不存在this指针的概念

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <queue>
#include "main.h"
using namespace std;

class Compare {
public:
    Compare() = default;
    Compare(int age, int high):age(age),high(high){};
    ~Compare() = default;
    void display()
    {
        printf("age = %d, high = %d\n", age, high);
    }
    friend Compare operator+(Compare& comp1, Compare& comp2); // 友元函数:重载运算符
private:
    int age;
    int high;
};

Compare operator+(Compare& comp1, Compare& comp2)
{
    Compare temp;
    temp.age = comp1.age + comp2.age;
    temp.high = comp1.high + comp2.high;
    return temp;
}

int main()
{
    Compare comp3(20, 186);
    Compare comp4(25, 190);
    Compare result = operator+(comp3, comp4);
    result.display();
    return 0;
}
posted @ 2021-03-17 01:11  WangCoder  阅读(74)  评论(0编辑  收藏  举报