所以这是原始代码:
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 size是否与IntegerArray类中声明的int大小相同?
data = new int[size]
只是告诉我们数据是以int大小指向数组的输出吗?新的说法是数组的大小是可变的吗?
this-> size = size
只是一个指针,告诉我们构造函数的大小值是否等于类的size参数?
在IntegerArray arr(2)之后为什么会提到arr.data[0]
和arr.data[1]
?他们似乎并不遵循构造函数,但我可能太累了,无法理解那部分。
答案 0 :(得分:2)
IntegerArray(int size) { data = new int[size]; this->size = size; }
int size与...相同
这int size
:
IntegerArray(int size) {
^^^^^^^^
是构造函数的参数
data = new int[size]
只是告诉我们......
new int[size]
动态分配包含size
个int
个对象的数组。然后指定data
指针指向新创建的数组。
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)
?
构造函数不初始化数组的内容(数组中的整数对象)。提到的代码会为它们分配一个值。
答案 1 :(得分:1)
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;
}
delete [] arr.data;应该在你班级的析构者里面......