void Classname::operator()(){ .... } 的作用是什么?
我正在研究一些 C++ 代码,并遇到以下内容,
void Classname::operator()()
{
//other code here
}
我认为这与重载构造函数有关,但有人可以详细说明吗?
Im working my way through some C++ code and came across the following
void Classname::operator()()
{
//other code here
}
I assume this has something to do with overloading the constructor, but can someone elaborate on that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
operator()
是函数调用运算符。它允许您像函数一样使用类实例:这对于函子和各种其他 C++ 技术很有用。您本质上可以传递一个“函数对象”。这只是一个具有
operator()
重载的对象。因此,您将其传递给函数模板,然后函数模板像调用函数一样调用它。例如,如果定义了Classname::operator()(int)
:这将调用
instance
的operator()(int)
成员对于列表中的每个整数。您可以在instance
对象中拥有成员变量,以便operator()(int)
可以执行您需要的任何处理。这比传递原始函数更灵活,因为这些成员变量是非全局数据。operator()
is the function-call operator. It allows you to use a class instance like a function:This is useful for functors and various other C++ techniques. You can essentially pass a "function object". This is just an object that has an overload of
operator()
. So you pass it to a function template, who then calls it like it were a function. For example, ifClassname::operator()(int)
is defined:This will call
instance
'soperator()(int)
member for each integer in the list. You can have member variables in theinstance
object, so thatoperator()(int)
can do whatever processing you require. This is more flexible than passing a raw function, since these member variables are non-global data.它使您的类成为一个称为“函子”的对象...它通常用作闭包类型对象,以便在该对象中嵌入一个状态,然后调用该对象,就好像它是一个函数一样,但是一个函数具有“状态性”,而没有全局可访问静态变量的缺点,就像尝试使用内部静态变量管理“状态”的传统 C 函数一样。
例如,
Classname
的实例可以像class_name_instance()
一样调用,并且其行为类似于不带参数的void
函数。It makes your class an object called a "Functor" ... it's often used as a closure-type object in order to embed a state with the object, and then call the object as-if it were a function, but a function that has "state-ness" without the downside of globally accessible static variables like you would have with traditional C-functions that attempt to manage a "state" with internal static variables.
For instance, with
An instance of
Classname
can be called likeclass_name_instance()
, and will behave like avoid
function that takes no arguments.它不是重载构造函数——而是重载函数调用运算符。如果您为类定义了 this,那么您可以调用该类的实例,就好像它是一个函数一样。这样的对象通常称为函子。
It's not overloading the constructor -- it's overloading the function-call operator. If you define this for a class, then you can invoke an instance of the class as if it were a function. Such an object is generally called a functor.
这是重载运算符“()”的代码,它基本上允许您将类用作不带参数的函数,您还可以有类似的内容:
有关重载的更多信息,您可以检查:
Operators_in_C_and_C++
That's the code to overload the operator '()' which basically allows you to use the class as a function with no parameters, you could also have something like:
For more info on overloading you can check:
Operators_in_C_and_C++