Why strange behaviour with operator()? [duplicate]

2019-09-25 11:04发布

问题:

This question already has an answer here:

  • My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it? 5 answers

I have simple class,

class Func
{
public:
    Func()
    {
        cout<<"Constructor"<<endl;
    }

    int operator()(int)
    {
        cout<<"Operator ()";
        return 0;
    }
};
  1. 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?
  2. 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?

回答1:

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 called f returning a Func. Everything you try to do with f after that is, naturally, broken.



回答2:

This is a bit interesting here.

Func f();

is a forward declaration for a function, which takes no argument and return Func type object.

Check the below code:

#include <iostream>
using namespace std;

class Func
{
public:
    int operator()(int)
    {
        return 0;
    }
};

int main ()
{
    Func f();
    f();
    return 0;
}

Func f ()
{
    cout << "My Func" << endl;
    Func * f = new Func;
    return *f;
}

It will output "My Func" on stdout.