2013-04-05 82 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

相關問題