本文介绍了为什么奇怪的行为与operator()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有简单的类,
class Func
{
public:
Func ()
{
cout<<Constructor<< endl;
}
int operator()(int)
{
cout<<
return 0;
}
};
- 当我通过括号创建对象时,
Func f();
,它什么也不打印,应该打印 Constructor 。但是当我创建没有括号的对象时,它会打印预期的 Constructor 。 - 当我尝试使用operator()
f(2)
它给我编译错误。
以下是创建 Func
的方法:
Func f;
是的,很奇怪,但这并不意外。当你写了 Func f()
时,你声明了一个名为 f
的函数返回 Func
。
f
之后,你尝试做的一切,自然是破碎的。
I have simple class,
class Func
{
public:
Func()
{
cout<<"Constructor"<<endl;
}
int operator()(int)
{
cout<<"Operator ()";
return 0;
}
};
- When I create it's object by giving parenthesis,
Func f();
, it prints nothing, it should print Constructor. But when I create object without parenthesis it prints Constructor which is expected. What is the different between these two? - When I try to use operator()
f(2)
it gives me compilation error.
Isn't it strange behaviour or I am missing something?
解决方案
That is not true whatsoever.
Here is how you create a Func
:
Func f;
Yes, it's strange, but it's not unexpected. When you wrote Func f()
you declared a function called f
returning a Func
. Everything you try to do with f
after that is, naturally, broken.
这篇关于为什么奇怪的行为与operator()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!