c++ 中重载 () 的理解,以及如何引申到函数对象

先看下面代码:

class StringSort
{
public:
	bool operator() (const string &str1, const string &str2) const
	{
		return str1 > str2;
	}
};

看的云里雾里。
没关系,我们先理解下面的代码:

class StringSort
{
public:
	bool sort (const string &str1, const string &str2) const
	{
		return str1 > str2;
	}
};

是不是很简单,就是把 sort 重载而已。
如何调用?创建一个对象 stringSort,调用 stringSort.sort(s1, s2)。注意不能用类直接调用,函数不是静态的。
可以类比 operator(),用 stringSort.operator(s1, s2) 调用。
由于 operator 是为了强调这是个运算符重载,因此可以简写成 stringSort(s1, s2)。这种写法是不是和构造函数相似?但他们区别大着呢。这种重载 () 是通过对象调用,只是对象的一个函数而已;而构造函数是通过类调用,进而生成一个新对象。可通过以下代码加深理解:

#include <iostream>
using namespace std;
class Clastype
{
    public:
        Clastype(int a)
        {
            cout << "Hello Clastype!" << a << endl;
        }
        bool operator ()(int b)
        {
            cout << "Hello Clastype()!" << b << endl;
            return true;
        }
};
int main()
{
    Clastype a(1);
    Clastype(2);
    Clastype t = Clastype(3);
    t(4);
    Clastype *b = new Clastype(5);
    (*b)(6);
}

结果为:

Hello Clastype!1
Hello Clastype!2
Hello Clastype!3
Hello Clastype()!4
Hello Clastype!5
Hello Clastype()!6

重载 () 作用:
对象的函数调用更方便。还有呢?这里就引出了函数对象的概念及作用。
函数对象:即一个重载了括号操作符“()”的对象(也就是上面的 stringSort)。当用该对象调用此操作符时,其表现形式如同普通函数调用一般,(stringSort 调用 () 函数的写法:stringSort.operator(s1, s2) 或 stringSort(s1, s2),后者 stringSort 看起来就像是一个函数)因此取名叫函数对象。
接着转到 函数对象 以继续了解。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值