0

可能重复:
为什么使用空括号调用不带参数的构造函数是错误的?
最令人头疼的解析:为什么不 A a(()); 工作?

这让我很生气。也许它太简单了。

struct Foo
{
  Foo() {}
  Foo(const Foo& f) {}
  void work() {}
};

int main()
{
  Foo f( Foo() );
  f.work();
}

GCC 4.6 给了我:

error: request for member ‘work’ in ‘f’, which is of non-class type ‘Foo(Foo (*)())’

省略复制操作后,有效代码可能如下所示:

int main()
{
  Foo f;
  f.work();
}

但是为什么我不能打电话work()??

编辑:

是的,重复(见下文)。第一次搜索时没有找到原始帖子,因为这个症状的来源位于我没想到的地方。

4

4 回答 4

3

因为Foo f( Foo() );是函数声明。

我想你想要:Foo f;

或者如果您想复制构造:

Foo f( (Foo()) );
于 2012-07-26T11:12:55.350 回答
1

f 实际上是 main 函数中的函数声明。尝试

Foo f((Foo())); // to make the definition of f explicit enough.
于 2012-07-26T11:13:56.317 回答
1

n3337 8.2

The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in 6.8 can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct that could possibly be a declaration a declaration. [ Note: A declaration can be explicitly disambiguated by a nonfunction-style cast, by an = to indicate initialization or by removing the redundant parentheses around the parameter name. — end note ] [ Example:

struct S {
S(int);
};
void foo(double a) {
S w(int(a));
//function declaration
S x(int());
//function declaration
S y((int)a);
//object declaration
S z = int(a);
//object declaration
}

— end example ]

于 2012-07-26T11:17:21.210 回答
1

C++ parser interprets Foo f(Foo()); expression as the function declaration with the signature Foo(Foo(*)()), i.e. a function returning Foo and taking a function pointer to the function returning Foo. Adding explicit parenthesis around the argument like so Foo f((Foo())); will resolve the ambiguity. But consider actually just doing Foo f; which avoids redundant code.

于 2012-07-26T11:18:00.607 回答