Why strange behaviour with operator()? [duplicate]

我与影子孤独终老i 提交于 2019-12-14 03:29:36

问题


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.



来源:https://stackoverflow.com/questions/28598673/why-strange-behaviour-with-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!