为什么不“foo f();”调用类“foo”的构造函数?

问题描述:

可能重复:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?为什么不“foo f();”调用类“foo”的构造函数?

我碰到了下面的问题。我创建了2个foo实例。 然后我意识到,foo f();没有执行一个类的构造函数。这是为什么?

class foo{ 
public: 
    foo() {cout <<"executed contructor...";} 
}; 

int main() { 
    foo f(); // doesn't run the ctor???? why? 
    foo f2; // this one does execute the ctor 


    system("pause"); 
    return 0; 
} 
+2

看到这个前面的问题http://*.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets- to-call-a-constructor-with-no – 2012-02-05 15:38:06

+0

搜索最烦人的语法分析 – 2012-02-05 15:42:27

+1

'foo f3(foo());'是最令人头痛的解析的例子。 'foo f();'只是一个令人头痛的解析。 – 2012-02-05 15:43:23

第一个声明一个函数。尝试访问名为f的对象。编译器会沿着这样的方向投诉:f有非类型foo(),这意味着它是一个不带参数并返回foo类型的对象的函数。

检查C++ FAQ问题10.2:

[10.2]有清单X之间的任何差别;和List x();?

http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.2