2013-04-05 78 views
3

我有以下两类:是否允许实例化一个类没有指定的变量名在C++

class Foo 
{ 
public: 
     Foo() { std::cout << "in Foo constructor" << std::endl; } 
}; 
class Bar 
{ 
public: 
    Bar() {}; 
    Bar(Foo foo); 
private: 
    Foo m_foo; 
}; 

Bar::Bar(Foo foo) : 
    m_foo(foo) 
{ 
    std::cout << "in Bar constructor with argument Foo" << std::endl; 
} 

int main() { 
    Bar bar(Foo()); // is something wrong here ? 
    return 0; 
} 

我编译和excuted吧,没什么显示在屏幕上,什么也Bar bar(Foo())办? 我看到Do the parentheses after the type name make a difference with new?Foo f = Foo(); // no matching function for call to 'Foo::Foo(Foo)'的相似性,但我仍然无法弄清楚。

+4

最令人头疼的解析。 – Pubby 2013-04-05 04:10:52

+1

的确最令人烦恼的解析。看看http://en.wikipedia.org/wiki/Most_vexing_parse! – Nbr44 2013-04-05 04:13:19

回答

1

要达到同样不改变语义(即not using the copy or assignment constructor),加括号来消除歧义的语法(编译器不知道你是否在本地声明函数,或者如果你建立一个对象,默认情况下,前由C++标准)优先:

int main() { 
    Bar bar ((Foo())); 
    return 0; 
} 

如被张贴在评论中Wikipedia page指出,它与C++语法本身,没有太多可以做些什么的问题。

+0

'Bar bar = Foo();'会做同样的事情(通过构造函数进行转换)。 – jxh 2013-04-05 05:37:10

+0

好的。如果'Foo'有一个转换操作符到'Bar'会怎么样? – Mic 2013-04-05 05:38:38

+1

如果'Bar'定义了一个需要'Foo'的构造函数,则优先。 – jxh 2013-04-05 05:43:35

0

好吧,已经指出compiler thinks that you are declaring a function。通过PubbyNbr44。这是一种如何避开它的方法。让编译器知道你正在声明变量。

int main() { 
    Bar bar = Foo(); 
    return 0; 
} 
+0

只是'酒吧= Foo();'就足够了。 – jxh 2013-04-05 04:29:07

+0

警告,语义不一样,你最终会在这里调用赋值操作符。例如,请参阅[此SO帖子](http://stackoverflow.com/questions/2462773/c-copy-construct-construct-and-assign-question)。 – Mic 2013-04-05 04:30:45

+0

没错,没有意识到。编辑... – Kupto 2013-04-05 04:32:23

相关问题