如何在c++中调用operator()
在 C++ 中我有以下代码
class Foobar{
public:
Foobar * operator()(){
return new Foobar;
};
我的问题是如何调用 (); 如果我执行 Foobar foo() 构造函数将被调用 我对 () 的行为感到困惑 有人可以解释一下吗
in c++ i have following code
class Foobar{
public:
Foobar * operator()(){
return new Foobar;
};
My quesion is how to call the ();
if i do Foobar foo() the constructor gets called
i am confused about behaviour of ()
can some explain me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然 GMan 的答案事实上是正确的,但你永远不应该重载操作符来做一些意想不到的事情 - 这违背了所有良好实践的编程规则。当用户阅读代码时,他期望操作员以某种方式表现,而让他们表现不同只会有利于混淆编码竞赛。
C++ 中的
()
运算符可用于使对象表示函数。它实际上有一个名字 - 它被称为函子,并在 STL 中广泛使用以提供通用算法。 Google 搜索 stl functor 以了解该技术的良好用法。While GMan's answer is factually correct, you should never overload an operator to do something unexpected - this goes against all good-practice programming rules. When a user reads code he expects operators to behave in some way, and making them behave differently is good only for obfuscating coding competitions.
The
()
operator in C++ can be used to make an object represent a function. This actually has a name - it's called functor, and is used extensively in the STL to provide generic algorithms. Google for stl functor to learn about a good usage of the technique.像这样:
这也很奇怪,因为返回这样的指针并且它是一个相当无用的函数。 (我“需要”一个
Foobar
来制作一个新的?)Like this:
Also this is very weird, in terms of returning a pointer like that and it being a rather useless function. (I "need" a
Foobar
to make a new one?)