2011-09-04 63 views
-4

我的問題與C++ 11標準和this old question的發佈有關,因爲我想知道現在是否可以在函數調用中創建數組/矢量,而不是構建數組/向量之前,然後只是將它作爲方法/函數的參數。在函數調用中初始化數組

+2

用詞重試。 –

+0

你的意思是「用詞」,我的問題是不可理解的,或者不知何故? – Sim

+1

這是100%美味模糊。 –

回答

2

(假設你在談論C++ 11)


void f(int x[]) {}   // remember, same as void f(int* x) {} 
int main() { f({0,1,2}); } 

// error: cannot convert '<brace-enclosed initializer list>' 
//   to 'int*' for argument '1' to 'void f(int*)' 

但是:

void f(const int (&x)[3]) {} 
int main() { f({0,1,2}); } 

// <no output> 

和:

void f(std::array<int, 3> x) {} 
int main() { f({0,1,2}); } 

// <no output> 

而且,順便說一句:

void f(std::vector<int> x) {} 
int main() { f({0,1,2}); } 

// <no output> 

所以基本上,但有注意事項。

+1

另一個警告:很少有編譯器實際上支持這個。據我所知,只有GCC。 –

+1

事實上,鏗鏘3.0不太滿意它。不過,我在這裏談論的是這個語言,而不是一些實現;並最終他們_都會支持它! –