仿函数(function-like class)
仿函数就是一种看起来就像是函数的类,其实是对“()”的重载。
class Func{
public:
void operator() (const string& str) const {
cout<<str<<endl;
}
};
int main(){
Func myFunc;
myFunc("helloworld!");
return 0;
}
结果:
helloworld!
如果你之前用过其他的操作符重载就会发现“()”的重载的用法是很奇怪的,应该写成myFunc()("helloworld!")
举个例子:
class Func{
public:
void operator+ (const string& str) const {
cout<<str<<endl;
}
};
int main(){
Func myFunc;
myFunc+"helloworld!";
return 0;
}
结果:
helloworld!
通过对比就可以发现“()”的重载的用法与其他操作符的重载用法不同,直接省略了一个括号没有什么难懂的,记住就要了。
像指针的类(pointer-like class)
pointer-like class顾名思义,就是我们的类的用法跟一个指针十分相似,上代码:
#include<iostream>
#include<string>
using namespace std;
struct Foo{
string str;
int n;
void funct(void){cout << str << endl;}
};
template <typename T>
class shared_ptr{
public:
T& operator* () const{ return *px;}
T* operator-> () const{ return px;}
shared_ptr(T* p) :px(p) {}
private:
T* px;
};
int main(){
shared_ptr<Foo> f = new Foo;
*f = {"helloworld",666};
cout << f->n << endl;
f->funct();
return 0;
}
结果:
666
helloworld
值得注意的是这一句:
f->funct();
如果严格按照符号重载的格式来写应该是这样的:
f->->funct();//错误写法
但是这确是不对的,编译器在其中做了手脚,我们记住这里的特殊用法就好了,就像“()”的重载一样需要记住。
还有就是*星花的重载,星花的重载是放在表达式左边使用的*f,而不是右边。