c++ - 在 C++ 中使用静态变量访问数组位置

标签 c++ arrays visual-studio static

我正在尝试将对象分配给数组位置。该位置由包含数组元素数的静态变量 (int) 给出。 tEntities 的大小是 5,fFuncionesList 的大小是 4,所以这不是大小问题。

if (TEntity::uEntityCount < 5)
        {
            iRandFuncList = rand() % (3 + 1);
            iRandPosX = rand() % (120 + 1);
            iRandPosY = rand() % (30 + 1);
            tEntities[TEntity::uEntityCount] = new TEntity((fFuncionesList[iRandFuncList]), iRandPosX, iRandPosY);
        }

TEntity(funcEntity *funcs, int x, int y)
    {
        m_ix = x;
        m_iy = y;
        m_funcs = funcs;
        uEntityCount++;
    }

Error Debuger

我试图将静态变量的值赋给一个 int 变量并且它有效,我想了解为什么它不适用于静态变量。

if (TEntity::uEntityCount < 5)
            {
                iRandFuncList = rand() % (3 + 1);
                iRandPosX = rand() % (120 + 1);
                iRandPosY = rand() % (30 + 1);
                int pos = TEntity::uEntityCount;
                tEntities[pos] = new TEntity((fFuncionesList[iRandFuncList]), iRandPosX, iRandPosY);
            }

提前致谢。

最佳答案

当你调用构造函数时你的问题就来了

tEntities[TEntity::uEntityCount] = new TEntity((fFuncionesList[iRandFuncList]),...);

它增加了 uEntityCount

uEntityCount++;

然后你将对象指针分配给 tEntities[TEntity::uEntityCount] 它将被放置在下一个位置,所以如果当前 uEntityCount=4 它将把指针放置在你数组之外的 uEntityCount=5

关于c++ - 在 C++ 中使用静态变量访问数组位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58899325/

相关文章:

c++ - 为 Mac OS X 修改旧的 Windows 程序

c++ - 如何解决 for 循环中的差一问题

c++ - 尝试在 C++ 中的 2 个类文件之间使用全局二维数组

c++ - 类似C语言的数组大小分配

visual-studio - 重新安装 Visual Studio 2015 后无法打开 SSIS 包(.dtproj 文件)

C#注释技术/注释重用

c++ - 由于 "incorrect configuration error",VC++ 应用程序无法在其他计算机上运行

C++串口库对Win32同步函数的使用?

c++ - 如何对动态数组执行操作?

visual-studio - 无法将 "obj\Debug\{project}.dll"复制到 "bin\{project}.dll"