理解这段涉及指针、数组和新运算符的代码
Understanding this code involving pointers, arrays, and the new operator
所以这是原始代码:
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;应该在类的析构函数内。。。
- 为什么模数运算符不适用于该代码
- 逻辑运算符上出现错误代码 a')'
- 如何使基类的运算符对基类的可变参数数可见(请参阅下面的代码)?
- std::string == 运算符在代码中不起作用
- 将 c++ 代码转换为 python,使用运算符?
- 为什么无法覆盖涉及第三方代码的模板类的运算符<<?
- 重载 <= 运算符,但程序以退出代码 -1073741571 (0xC00000FD) 结尾
- 如何翻译这个给定代码中的 ::* 运算符和member_fn?
- 代码块编译错误与运算符<<不匹配
- 为多个签名使用相同的代码重载赋值运算符?
- 赋值运算符在我制作类模板时使代码崩溃
- 在使用具有相等运算符定义的抽象类时,如何定义父类以减少代码重复?
- 删除运算符如何在我的代码中工作
- 在混合 c 和 c++ 代码中使用运算符 new
- 任何机构都可以在运算符重载中解释这行代码
- 没有运算符"[]"匹配这些操作数/没有模板化代码
- 试图重写代码以包括模量运算符
- 重载新运算符 - 此代码不应产生错误
- Visual studio:E0349 没有运算符<<匹配这些操作数(但代码中没有字符串)
- C++类型转换运算符代码,在 Visual Studio 2012 中无法编译,但在 Visual Studio 2005 中工作正常