Determine array size in constructor initializer

前端 未结 12 2402
失恋的感觉
失恋的感觉 2020-12-08 21:10

In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that?

class Class
{
public:
  int         


        
12条回答
  •  死守一世寂寞
    2020-12-08 21:35

    Don't you understand there is not need to use vector, if one wants to use arrays it's a matter of efficiency, e.g. less space, no copy time (in such case if handled properly there is not even need to delete the array within a destructor), etc. wichever reasons one has.

    the correct answer is: (quoted)

    class Class
    {
       int* array;
       Class(int x) : array(new int[x]) {};
    };
    

    Do not try to force one to use non optimal alternatives or you'll be confusing unexperienced programmers

提交回复
热议问题