随笔——运算符重载

//+,-,运算符重载
#include<iostream>
using namespace std;
class node
{
private:
    int x,y;
public:
    node(){};
    node(int a,int b)
    {
        x=a,y=b;
    }
    init()
    {
        cin>>this->x>>this->y;
    }
    out()
    {
        cout<<x<<" "<<y<<endl;
    }
    node operator + (const node& b);
    friend node operator - (const node& a,const node &b);//把全局函数定义为友元,函数需要访问x,y.
};
node node::operator + (const node & b)//成员重载函数
{
    return node(x+b.x,y+b.y);//构造函数重载后,可以直接通过构造函数返回。
}
node operator - (const node& a,const node &b)//全局重载函数
{
    return node(a.x-b.x,a.y-b.x);
}
int main()
{
    int x,y;
    node a,b,c;
    a.init();
    b.init();
    c=a+b;
    cout<<"a+b=";
    c.out();
    c=a-b;
    cout<<"a-b=";
    c.out();
}
/*
+,-,*,/,四个运算符重载方法基本相同,运算符为全局函数时,参数函数等于运算符
的目数,运算符为成员函数时,参数个数等于运算符的目数减一。
*/
//=运算符重载
#include<iostream>
#include<string.h>
using namespace std;
class String
{
private:
    char *str;
public:
    String operator = (const char *s)
    {
        if(str)
        {
            delete[]str;//如果str不为空,删除它,节省空间。
            str=NULL;
        }
        if(s)
        {
            str=new char[strlen(s)+1];//为str开辟新内存,
            strcpy(str,s);
        }
        return *this;//不写也行。
    }
    out()
    {
        cout<<str<<endl;
    }
};
int main()
{
    String a;
    a="123456";
    a.out();
}
/*
等号运算符重载方式和其他二元运算符重载方式基本相同,可需要实现的功能和其他
运算符有一些不同,需要注意空间释放等事项。
*/

//运算符重载为友元函数
#include<iostream>
using namespace std;
class node
{
private:
    int x;
public:
    node(){};
    node(int a):x(a){};
    node operator + (int a)//成员函数运算符重载
    {
        return node(a+x);
    }
    friend node operator + (int a,node b);//声明友元
    out()
    {
        cout<<x<<endl;
    }
};
node operator + (int a,node b)//全局运算符重载
{
    return node(a+b.x);
}
int main()
{
    node a(2);
    a.out();
    a=a+5;
    a.out();
    a=10+a;
    a.out();
}
/*
有时候,为了实现一些特定的功能,需要把类的运算符重载成全局函数,而又需要保证类的密封性
不被破坏。一个类node,有时候希望node+5,5+node,这两个算式都解释的通,而node+5可以使用
类的重载来解释,可5+node呢?这时候就需要用到再次重载,重载为全局函数,全局函数无法访问类
的私有成员,这时候就需要用到friend来声明其函数为类的友元,便已访问类内的私有成员。
*/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值