为什么我不能访问全局范围中的数组下标 [英] Why can't I access my array subscript in global scope

查看:293
本文介绍了为什么我不能访问全局范围中的数组下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一个函数中有下面的代码,我不会得到一个错误,我可以编译没有问题,但是,一旦我把它放在全局范围内,我会得到一个错误不能分配一个大小为零的数组, ,以及其他几个错误。为什么会发生这种情况,如何摆脱错误。我知道全局变量的风险,这只是一个简单的测试用例。

If I have the following code in a function, I will not get an error and I can compile no problem, however, once I put it in global scope I will get an error for "cannot allocate an array of size zero", along with several other errors. Why does this happen and how can I get rid of the errors. I am aware of the risk of global variables, this is just a simple test case.

int* intest[2];
intest[0] = new int;


推荐答案

您可以在全局范围内声明,但不允许使用new操作符或赋值。因此,你需要在全局范围中的声明int * intest [2](和所有的代码都会看到它),但C ++要求新的是在你的主要代码的序列。 (可能是在某种类型的启动函数的应用程序)。

You are allowed declarations in global scope but not allowed to use the new operator or the assignment. Thus you need the declaration int *intest[2] in global scope (and all your code would see it) but C++ requires the new to be in the sequence of your main code. (probably in some sort of start up function for the app).

编辑:如@phresnel指出,你可以使用在这个范围的新操作符, (这是不寻常的,但不是非法的)。但是,以下用作启动的新运算符将为您工作:

as pointed out by @phresnel you can use the new operator in this scope but not the assignment (this is unusual but not illegal). However the following new operators used as initiation will work for you:

int *x[2]={new int,new int};

一般来说,使用这种全局缓冲区是非常不鼓励的,被认为是一种反模式你可以避免使用它你可能应该。

In general the use of such a global buffer is highly discouraged and is considered an anti-pattern - if you can avoid using it you probably should.

这篇关于为什么我不能访问全局范围中的数组下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆