初识c++(14)之仿函数(function-like class)和像指针的类(pointer-like class)"()"和“->”和“*”的重载

仿函数(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,而不是右边。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值