下面我们来具体学习如何使用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[],->* 。
下列运算符不允许重载:
.
, .* ,
:: , ?:
2586

被折叠的 条评论
为什么被折叠?



