理解这段涉及指针、数组和新运算符的代码

Understanding this code involving pointers, arrays, and the new operator

本文关键字:运算符 代码 数组 段涉 指针      更新时间:2023-10-16

所以这是原始代码:

class IntegerArray { 
public:   
int *data;   
int size; 
};  
int main() {   
IntegerArray arr;   
arr.size = 2;   
arr.data = new int[arr.size];   
arr.data[0] = 4; arr.data[1] = 5;   
delete[] a.data; 
}

arr.data = new int[arr.size]移动到构造函数后,它将成为

class IntegerArray { 
public:   
int *data;   
int size;   
IntegerArray(int size) {     
data = new int[size];     
this->size = size;   
} 
};  
int main() {   
IntegerArray arr(2);   
arr.data[0] = 4; arr.data[1] = 5;      
delete[] arr.data; 
}

我对代码试图做的事情相当困惑。对于

IntegerArray(int size) {     
data = new int[size];     
this->size = size;   
} 

int大小是否与IntegerArray类中声明的int大小相同?

data = new int[size]是否只是告诉我们,数据指向int大小的数组输出,而新的说法是数组的大小是可变的?

this-> size = size是否只是一个指针,它告诉我们构造函数的大小值等于类的大小参数?

为什么在IntegerArray arr(2)之后还会提到arr.data[0]arr.data[1]?它们似乎没有遵循构造函数,但我可能太累了,无法理解这一部分。

IntegerArray(int size) {     
data = new int[size];     
this->size = size;   
} 

int大小与…相同吗。。。

int size:

IntegerArray(int size) {
^^^^^^^^

是构造函数的参数

data = new int[size]只是告诉我们。。。

new int[size]动态分配一个数组,该数组包含size个数量的int对象。CCD_ 11指针然后被分配来指向新创建的数组。

this-> size = size只是一个指针吗。。。

否。this是一个特殊的指针,它在构造函数中指向正在构造的对象。this->size是在此声明的成员变量:

class IntegerArray { 
public:   
int *data;   
int size;
^^^^^^^^

完整表达式this->size = size将作为构造函数参数的值size分配给成员变量size

为什么arr.data[0]arr.data[1]甚至在IntegerArray arr(2)之后被提及?

构造函数不会初始化数组的内容(数组中的整数对象)。上面提到的代码确实为它们分配了一个值。

this->size = size //the fist size is your member variable which is inside IntegerArray. the 2nd size is the size you give over to the Method
data = new int[size];  // here you are creating a new array with the size of "size"

方法IntegerArray(int size)是一个构造函数方法,每个对象只能调用一次(即使在创建对象时)

int main() //the startpoint of your program
{   
IntegerArray arr(2);   //you are creating a new object with a size of 2
arr.data[0] = 4; arr.data[1] = 5;   //because of your array is public, you can call it direct from outside (you sould define it as private ore protected). arr.data[0] is the first item of the array, arr.data[1] is the 2nd item
delete[] arr.data; 
} 

删除[]arr.data;应该在类的析构函数内。。。