c++运算符重载

下面我们来具体学习如何使用c++重载;

   重载函数的格式:<返回值类型> operator <要重载的运算符>const  结构体名)const{ . . . }

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Comp{
    int a,b;
    //第一个const 如果传入参数不会被改变最好加上const修饰
    //第二个const 重载函数只读
    bool operator < (const Comp &c) const{
      if(a!=c.a)
         return a<c.a;
      return b<c.b;
    }

};
int main()
{
    vector<Comp> v;
    v.push_back({3,4});
    v.push_back({1,2});

    vector<Comp>::iterator it;

    if(!(v[0]<v[1]))//实现了"<" 的重载
        cout<<"小于"<<endl;
 
    for(it=v.begin();it!=v.end();it++)
        cout<<it->a<<"  "<<it->b<<endl;

    return 0;
}
重载函数在外部实现:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Comp{
    int a,b;
    //第一个const 如果传入参数不会被改变最好加上const修饰
    //第二个const 重载函数只读
    bool operator < (const Comp &c) const{
      if(a!=c.a)
         return a<c.a;
      return b<c.b;
    }
    bool operator == (const Comp& c) const;//声明
};
//"=="的重载 两个数组对象相等
bool Comp::operator==(const Comp &c)const
{
     return this->a==c.a&& this->b==c.b;
     //注意this 是指针 
}
int main()
{
    vector<Comp> v;
    v.push_back((Comp){3,4});//强制造型,(Comp)
    v.push_back({1,2});
    v.push_back({1,2});

    vector<Comp>::iterator it;


    if((v[1]==v[2]))//实现了"<" 的重载
        cout<<"==于"<<endl;

    for(it=v.begin();it!=v.end();it++)
        cout<<it->a<<"  "<<it->b<<endl;

    return 0;
}


总结:

在c++中  几乎所有的运算符都可用作重载。具体包含:

    算术运算符:+,-,*,/,%,++,--;

    位操作运算符:&,|,~,^,<<,>>

    逻辑运算符:!,&&,||;

    比较运算符:<,>,>=,<=,==,!=;

    赋值运算符:=,+=,-=,*=,/=,%=,&=,|=,^=,<<=,>>=;

    其他运算符:[],(),->,,(逗号运算符),new,delete,new[],delete[],->* 。

下列运算符不允许重载:

        . , .* , :: , ?:










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值