开发者

how to call operator () in c++

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


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.


Like this:

Foobar f;
Foobar* p = f(); // f() invokes operator()
delete p;

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?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜