为什么奇怪的行为与operator()? [英] Why strange behaviour with operator()?
问题描述
我有简单的类,
class Func
{
public:
Func ()
{
cout<<Constructor<< endl;
}
int operator()(int)
{
cout<<
return 0;
}
};
- 当我通过括号创建对象时,
Func f();
,它什么也不打印,应该打印 Constructor 。但是当我创建没有括号的对象时,它会打印预期的 Constructor 。 - 当我尝试使用operator()
f(2)
它给我编译错误。
错误C2660:'f':function不接受1个参数
$ b $解决方案
Func f();它不打印任何内容,应打印构造函数
以下是创建
Func
的方法:Func f;
当我尝试使用operator()f我编译错误。错误C2660:'f':函数不接受1个参数。
是的,很奇怪,但这并不意外。当你写了
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.
error C2660: 'f' : function does not take 1 arguments
Isn't it strange behaviour or I am missing something?
解决方案Func f();, it prints nothing, it should print Constructor
That is not true whatsoever.
Here is how you create a
Func
:Func f;
When I try to use operator() f(2) it gives me compilation error. error C2660: 'f' : function does not take 1 arguments. Isn't it strange behaviour or I am missing something?
Yes, it's strange, but it's not unexpected. When you wrote
Func f()
you declared a function calledf
returning aFunc
. Everything you try to do withf
after that is, naturally, broken.这篇关于为什么奇怪的行为与operator()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!