为什么奇怪的行为与operator()? [英] Why strange behaviour with operator()?

查看:159
本文介绍了为什么奇怪的行为与operator()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的类,

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

int operator()(int)
{
cout<<
return 0;
}
};




  1. 当我通过括号创建对象时, Func f(); ,它什么也不打印,应该打印 Constructor 。但是当我创建没有括号的对象时,它会打印预期的 Constructor

  2. 当我尝试使用operator() f(2)它给我编译错误。




错误C2660:'f':function不接受1个参数

$ b $

解决方案


Func f();它不打印任何内容,应打印构造函数




以下是创建 Func 的方法:

  Func f; 




当我尝试使用operator()f我编译错误。错误C2660:'f':函数不接受1个参数。


是的,很奇怪,但这并不意外。当你写了 Func f()时,你声明了一个名为 f 的函数返回 Func f 之后,你尝试做的一切,自然是破碎的。


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?

解决方案

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.

这篇关于为什么奇怪的行为与operator()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆