zoukankan      html  css  js  c++  java
  • C++ 运算符重载一(二元运算符重载)

    //二元运算符重载
    #include<iostream>
    using namespace std;
    
    class Point
    {
    public:
        Point(int x,int y){
            this->x = x;
            this->y = y;
        }
        //为什么要使用友元函数呢
        friend Point operator+(Point &p1, Point &p2);
    
        //类成员函数实现二元运算符-
        Point operator-(Point &pin){
            //二元运算符最好不要改变原来的变量
            Point temp = *this;
            temp.x = this->x - pin.x;
            temp.y = this->y - pin.y;
            return temp;
        }
        void PrintfA(){
            cout << "x=" << this->x << endl;
            cout << "y=" << this->y << endl;
    
        }
    private:
        int x;
        int y;
    };
    
    //友元函数
    //因为函数中使用类的私有成员属性
    Point operator+(Point &p1, Point &p2){
        Point pres(p1.x+p2.x,p1.y+p2.y);
        return pres;
    }
    
    void ProtectA(){
        //重载二元运算符 +
        Point p1(1, 1), p2(2, 2);
        Point p3 = p1 + p2;
        //全局函数(一般是友元函数),类成员函数实现运算符重载步骤
        //步骤1:要承认操作符重载是一个函数,写出函数名称
        //operator+
        //步骤2:根据操作数,写出函数参数列表
        //operator+(p1, p2);
        //步骤3:根据业务,完成函数返回值,及实现函数
        //p3=operator + (p1, p2);
        p3.PrintfA();
    
        //用类成员们函数实现
        //由全局函数变成类成员函数
        Point p4 = p1 - p2;
        //步骤1:要承认操作符重载是一个函数,写出函数名称
        //operator-()
        //步骤2:根据操作数,写出函数参数列表,
        ///在类中,对象本身是this,所有可以少传递一个变量
        //p1.operator-(p2);
        //步骤3:根据业务,完成函数返回值,及实现函数
        p4.PrintfA();
    
    
    
    }
    
    void main(){
        ProtectA();
        system("pause");
    }
  • 相关阅读:
    Linux 文件排序
    ubuntu18.04 美化桌面
    git clone 加速
    ubunutu下图像编辑器安装
    vue.js实战教程 https://www.jb51.net/Special/978.htm
    原生JS实现多条件筛选
    php结合js实现多条件组合查询
    js前端 多条件筛选查询
    JS 判断字符串是否全部为数字
    GET请求中URL的最大长度限制总结
  • 原文地址:https://www.cnblogs.com/zhanggaofeng/p/5619421.html
Copyright © 2011-2022 走看看