问题描述
我想在我的类的头文件中声明一个指向整数数组的指针。我有
I want to declare a pointer to an integer array in the header file for my class. I have
private:
int *theName;
,然后在构造函数中
theName = new int[10];
这将有效吗?有没有另一种方法来这样做,所以你有一个指向数组的指针?
will this work? Is there another way to do this so you have a pointer to an array?
我想int * theName创建一个指向一个整数而不是一个整数数组,如果这创建一个指向整数数组的指针如何创建一个指向整数的指针?
I thought int *theName created a pointer to an integer not an integer array, if this creates a pointer to an integer array how do you create a pointer to just an integer?
同样在析构函数中,我可以调用
Also in the destructor can I call
delete theName; theName = NULL;
这会删除整数数组对象,然后将内存中的null指向null?
Will that delete theName integer array object and then point theName to null in memory?
感谢
推荐答案
四件事:
-
一个,是的,是如何使指针指向数组。请注意,指向整数的指针和指向整数的指针之间没有区别 ;您可以将整数视为一个元素的数组。如果
x
是指向整数的指针,您仍然可以使用x [0]
c $ c> * x 如果x
是指向数组的指针,它们工作方式相同。
One, yes that is how you make a pointer to an array. Notice that there's no difference between a pointer to an integer and a pointer to an integer array; you can think of an integer as an array of one element. You can still use
x[0]
ifx
is a pointer to an integer, and you can still use*x
ifx
is a pointer to an array, and they work the same.
其次,你必须使用 delete [] theName
,不 / code>。无论您使用 new
,您都必须使用 delete
,并且无论您使用 new []
您必须使用 delete []
。此外,不必设置 theName = NULL
,因为在析构函数运行后,您不能访问 theName
any
Secondly, you have to use delete[] theName
, not delete theName
. Wherever you use new
you have to use delete
, and wherever you use new[]
you have to use delete[]
. Also, it is unnecessary to set theName = NULL
because after the destructor is run, you can't access theName
any more anyway.
第三,当你写一个管理资源的类时,你需要写一个复制构造函数,移动构造函数,复制赋值操作符和移动赋值操作符
Thirdly, when you write a class that manages resources, you need to write a copy constructor, move constructor, copy assignment operator and move assignment operator.
第四,除非你只是做一个教学练习,否则应该使用 std :: vector
。它有许多优点,没有真正的缺点。如果使用向量
,你甚至不必写另外四个构造函数。
Fourthly, unless you are just doing this as a didactic exercise, you should really use std::vector
. It has many advantages and no real disadvantages. And you don't even have to write the four other constructors if you use vector
.
这篇关于声明指向整数数组C ++的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!