C++——操作符重载

什么是运算符重载?
我们使用operator关键字来拓展运算符的功能。

什么时候需要重载运算符?
重载运算符相当于封装,当我们重载了运算符之后。我们可以使用简单的运算符来实现复杂的功能。比如,用(+)加号来让两个对象相加。
我们通常把运算符重载用在类里面。当然,我们以可以定义成全局的。(不是所有的运算符都可以重载)

重载运算符的方法:
在类体里面声明需要重载的操作符,声明方式和普通函数一样,只是需要使用关键字operator,声明格式如下:
类名 operator (运算符)(const 类名 & 对象名,(其他参数));
这个函数的 我们通常把 operator (运算符):它们当作一个函数名。而第一个类名是这个函数的返回值类型。
例1: 重载加号运 类型 Box box3;
Box3.length = this->length + box1.length;
box3.breadth = this->breadth + box1.readth;
box3.height = this->height + box1.height;
return box3;
}
如果我们在类里声明,在类外面定义:可以清楚的看到格式
Box operator + (const Box & b);

Box Box::operator+(const Box &b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}

例2: 重载负运算符( - ) ,取距离的相反数
Distance operator - (const Distance & dis )
{
Distance d;
d.feet = -dis.feet;
d.inches = -ids.inches;
return d;
}

全局重载操作符
//重载之后的符号会失去原来的特性
注:类型必须是明确的
//通过年纪判断两个人的是否相同
bool operator== (person const & p1 ,person const& p2)
{
if (p1.age == p2.age)
{
return true;
}
else
{
return false;
}
}

函数运算符重载:仿函数
函数运算符: ()
//重载 函数运算符()
class Myprint
{
public:
void operator()(string name=nullptr)
{
cout<<“print test”<<name<<endl;
}
};

void test()
{
Myprint myPrint;
myPrint(“AAAAA”);
}

匿名对象
可以使用:类名+()代替对象名
例:
cout<<myPrint()()<<endl;
此时,Person()就是一个匿名对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值