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;
    }
    
  • 相关阅读:
    Redis——发布/订阅
    Redis——任务队列
    GOF设计模式——Builder模式
    GOF设计模式——Prototype模式
    GOF设计模式——Singleton模式
    shell 脚本中的数学计算表达
    shell $'somestring'
    shell if-elif-elif-fi
    vim 使用
    疑问:为什么要使用href=”javascript:void(0);”?
  • 原文地址:https://www.cnblogs.com/wangdongfang/p/14547003.html
Copyright © 2011-2022 走看看