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;
    }
    
  • 相关阅读:
    设计模式之-工厂模式、构造函数模式
    发布订阅小示例
    使用vue,react,angular等框架和不使用框架使用jquery的优缺点
    react优化--pureComponent
    Vue、 React比较
    ORACLE触发器和new、old特殊变量
    mysql的存储过程与自定义函数
    MySQL日期
    php(Personal Home Page)简介,安装和配置(apache服务器使用和配置1)
    话谈html语义化
  • 原文地址:https://www.cnblogs.com/wangdongfang/p/14547003.html
Copyright © 2011-2022 走看看