C++ 运算符重载一(二元运算符重载)

本文通过实例介绍如何在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");
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值