我正在尝试将数组传递给C ++中的构造函数,但它无法正常工作:
arrayClass(int *array,int size){
a = new int[15];
for(int i(0); i < size; i++) {
this->a[i] = array[i];
}
this->size = size;
cout << "In second constructor" << endl;
}
在main()
中int array[3]={1,2,3};
arrayClass a2(array,3);
答案 0 :(得分:1)
您的示例工作正常 - 在完成后,请相应地注意delete[]
new[]
分配的空间(以防止内存泄漏)。此外,您可能不想使用15作为硬编码常量,而是使用参数size
(否则对于大于15个元素的数组,您将遇到内存访问冲突)。
class ArrayClass{
public:
ArrayClass(int* array, int size){
a = new int[size];
for (int i(0); i < size; i++) {
this->a[i] = array[i];
}
this->size = size;
}
virtual ~ArrayClass(){
delete[] a;
}
private:
int* a;
int size;
};
int main(int argc, char** argv){
int array[3] = { 1, 2, 3 };
ArrayClass a2(array, 3);
return 0;
}
可以用不同的方式在C ++中分配数组:
int a[3]; // will allocate the space for 3 elements statically from the stack
int* a = new int[3]; // will allocate space for 3 elements dynamically from the heap
基本上它决定你的数组将在哪个内存中 - 但这两种方法有很多不同之处 - 参见ie What and where are the stack and heap?。 一些主要的区别是:
int size = 10; int a[size]; // <- is invalid
deleted[]
显式不泄漏内存行int* a = new int[3];
将向一个内存位置声明一个指针变量,其中3 int
个值可以适合。所以在声明之后这三个值可以直接作为a[0]
来解决, a[1]
和a[2]
。完成所有操作后,delete[] a;
是必要的。因为如果指针a*
超出范围(即函数结束),则不会自动释放3个值的内存。