大家好。我是一名经验丰富的 Java 程序员,正在学习 C++。
现在我有一点初学者的问题。我有一个 int 类型的数组变量 x。
用户会在方法B中输入x的大小,我想在方法A中使用x。
void method A()
{
using int x [] blah blah blah
}
void method B()
{
int n;
cin >>n;
int x [n]; // How can I use this int x in method A without getting error: storage size x is unknown.
// Or the error 'x' was not declared in this scope.
}
编辑:参数传递不是我正在寻找的解决方案。
双重编辑:我确实知道 vector 选项,但我的程序正在按时补习。我正在创建一种每一毫秒都很重要的算法。
顺便说一句,我找到了一种方法。
int x [] = {}
method B();
method A () { blah blah use x}
method B () {/*int*/ x [n]}
最佳答案
如果您实际上想要一个数组而不是一个 vector ,并且您希望该数组在运行时动态调整大小,您需要在堆上创建它(将它存储在一个指针中),并在完成后释放它。
来自 Java,您需要了解 C++ 中没有垃圾收集 - 您在对象中新建
(在堆上创建)的任何内容都需要在析构函数中使用 进行清理删除
。
class foo
{
private:
int *array;
public:
foo() { array = NULL; };
~foo()
{
if (array != NULL)
delete [] array;
}
void createArray()
{
array = new int[5];
}
};
关于C++ 初始化全局数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914992/