Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 通过构造函数初始化数组_C++_Arrays_Constructor - Fatal编程技术网

C++ 通过构造函数初始化数组

C++ 通过构造函数初始化数组,c++,arrays,constructor,C++,Arrays,Constructor,我有: 我想通过以下方式调用此类: class first{ private: int *array; public: first(int x){ array = new int[x][10]; } 为什么它不起作用?如何从构造函数中按大小精简数组???这就足够了: first class1 = new first(10); new用于分配指针时 first class1(10); 此外,这里还有一个不兼容: first *class1 = ne

我有:

我想通过以下方式调用此类:

class first{
   private:
   int *array;

   public:
   first(int x){
     array = new int[x][10];
   }
为什么它不起作用?如何从构造函数中按大小精简数组???

这就足够了:

first class1 = new first(10);
new
用于分配指针时

first class1(10);

此外,这里还有一个不兼容:

first *class1 = new first(10);
array
是一个
int*
,但是
newint[x][10]
是一个2D数组。我不知道你想要哪一个

对于1D阵列:

array = new int[x][10];
int *array;
array = new int[x];
对于2D阵列:

array = new int[x][10];
int *array;
array = new int[x];
也就是说,你最好还是使用它



旁注:既然构造函数中有内存分配,您也应该这样做。

您已经指出您想要一个一维数组(
int*
),但试图分配一个二维数组(
new[x][10]

我假设你需要一维

C++的方式是用<代码>向量< /代码> .<

int (*array)[10];
array = new int[x][10];
#包括
头等舱{
私人:
std::矢量阵列;
公众:
显式优先(int x):数组(x){
}
};

它以什么方式不起作用?它会崩溃吗?哪里它不编译吗?你的错误是什么?发生了什么?你期望什么?请提供详细信息。错误:无法将分配中的“int()[10]”转换为“int”。如何从构造函数按大小初始化二维数组??我不想使用向量…和复制赋值运算符(根据)。但是,除非您特别想让事情变得困难,否则请使用
std::vector
。对象不应该是指针。向量是另一回事。如何做到这一点?答案更新。多维数组可能会变得非常难看。所以我建议你使用
向量数组