C++ Array Initialization in Function Call or Constructor Call

冷暖自知 提交于 2020-01-03 16:41:09

问题


This question is related to the post here. Is it possible to initialize an array in a function call or constructor call? For example, class foo's constructor wants an array of size 3, so I want to call foo( { 0, 0, 0 } ). I've tried this, and it does not work. I'd like to be able to initialize objects of type foo in other objects' constructor initialization lists, or initialize foo's without first creating a separate array. Is this possible?


回答1:


Not in the current standard. It will be possible in C++11

In gcc you can use a cast to force the creation of a temporal, but it is not standard c++ (C99):

typedef int array[2];
void foo( array ) {}  // Note: the actual signature is: void foo( int * )
int main() {
   foo( (array){ 1, 2 } );
}



回答2:


If permitted by your design, you can consider wrapping the data inside a class and in default constructor initialize with 0 (or any value of your choice)



来源:https://stackoverflow.com/questions/2676697/c-array-initialization-in-function-call-or-constructor-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!