3.函数对象
可以直接调用类的构造函数产生一个临时对象,作为参数传递给函数实参
比如:
Class GT_cls{
public:
GT_cls(int val):bool(val){}
bool operator(const string s) ;
{return s.size()>=bound;}
private:
std::string::size_type bound;
};
然后
count_if(word.begin(),word.end(),GT_cls(6)); //count_if标准库算法 这里GT_cls先构造临时对象,然后count_if传递word对象进GT_cls然后调用函数()//C++ Primer里面的例子
再比如如下:
struct IterOp{
virtual void operator()(std::vector<char>::const_iterator& iter) = 0;
};
struct IterAdd : public IterOp{
void operator()(std::vector<char>::const_iterator& iter){++iter;}
};
struct IterSub : public IterOp{
void operator()(std::vector<char>::const_iterator& iter){--iter;}
};
IterOp* ops[] = {new IterAdd, new IterSub};for (; iter != flags[index]; ops[index]->operator()(iter)) //简单的显式调用
总结:
由上述可以得出,重载操作符跟函数对象也是函数,只不过分显式跟隐式而已。
编辑特别推荐:
VC++调用Fortran生成的DLL实例
① 凡本网注明稿件来源为"原创"的所有文字、图片和音视频稿件,版权均属本网所有。任何媒体、网站或个人转载、链接转贴或以其他方式复制发表时必须注明"稿件来源:我考网",违者本网将依法追究责任;
② 本网部分稿件来源于网络,任何单位或个人认为我考网发布的内容可能涉嫌侵犯其合法权益,应该及时向我考网书面反馈,并提供身份证明、权属证明及详细侵权情况证明,我考网在收到上述法律文件后,将会尽快移除被控侵权内容。