zoukankan      html  css  js  c++  java
  • 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
    ", 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
    ", 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;
    }
    
  • 相关阅读:
    leetcode hot 100- 84. 柱状图中最大的矩形
    leetcode hot 100- 221. 最大正方形
    leetcode hot 100-34. 在排序数组中查找元素的第一个和最后一个位置
    leetcode hot 100-剑指 Offer 37. 序列化二叉树
    leetcode hot 100-2. 两数相加
    leetcode hot 100-33. 搜索旋转排序数组
    leetcode hot 100- 98. 验证二叉搜索树
    leetcode hot 100-152. 乘积最大子数组
    leetcode hot 100-19. 删除链表的倒数第N个节点
    v-modal的使用。
  • 原文地址:https://www.cnblogs.com/wangdongfang/p/14547003.html
Copyright © 2011-2022 走看看