C ++对象数组堆栈溢出 [英] C++ Object array stack overflow

查看:48
本文介绍了C ++对象数组堆栈溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试创建一个'gameObject'数组时,我得到一个堆栈溢出异常,这可能是什么原因吗?对于1的数组,它不会引发异常,我误会了(只创建一个'gameObject'变量就可以了)

when i try to create an array of 'gameObject'-s i get a stack overflow exception, any idea what might be the reason? for an array of 1 it DOES NOT throw an exception, i was mistaken (creating just a 'gameObject' variable is fine)

我知道我的代码很乱,而且很糟糕,但是我对C ++还是很陌生,所以请原谅我的代码:(

I know my code is messy, and just all around bad, but i'm fairly new to c++ so please excuse my code :(

这是我的Main.cpp:

Here is my Main.cpp:

int main()
{
using namespace std::literals::chrono_literals;

HWND myconsole = GetConsoleWindow();
HDC mydc = GetDC(myconsole);

bool loop;
loop = false;

std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
std::chrono::duration<float> duration;

gameObject test(mydc, "test.dat");
gameObject objList[100];

test.posX = 200;
test.posY = 10;

std::cout << getCurrentId();

while (true)
{
    start = std::chrono::high_resolution_clock::now();



    if (GetKeyState(VK_DOWN) & 0x8000)
    {
        test.move(0, -3);       
    }

    if (GetKeyState(VK_UP) & 0x8000)
    {
        test.move(0, 3);
    }

    if (GetKeyState(VK_RIGHT) & 0x8000)
    {
        test.move(6, 0);
    }

    if (GetKeyState(VK_SPACE) & 0x8000)
    {
        gameObject shell(mydc, "shell.dat");
        shell.type = 1;
        shell.posX = test.posX + test.l;
        shell.posY = test.posY + test.h;
        objList[getCurrentId()] = shell;
    }

    if (loop == false)
    {
        for (int i = 0; i < 100; i++)
        {
            if (objList[i].type == 1)
            {
                objList[i].move(1, 0);
            }
        }
    }

    if (loop == false)
    {
        loop = true;
    }
    else
    {
        loop = false;
    }

    end = std::chrono::high_resolution_clock::now();
    duration = end - start;

    if (duration < 0.0333s)
    {
        std::this_thread::sleep_for(0.0333s - duration);
    }


}
}

这是'gameObject'类:

and here is the 'gameObject' class:

class gameObject
{
public:
    gameObject(HDC currentDc, std::string dataFile);
    gameObject();
    ~gameObject();

    void clear();
    void draw();

    void move(int x, int y);

    void loadSprite(std::string spriteName);

    bool collide(gameObject);

    unsigned short h = 1;
    unsigned short l = 1;

    int posX;
    int posY;

    unsigned short type;

    COLORREF spriteData[256][256];

    unsigned short id;




    HDC dc;
};

推荐答案

您正在堆栈上创建所有对象 gameObject objList [100]; ,每个对象中都有一个大数组 COLORREF spriteData [256] [256]; .那是你的堆栈溢出.

You are creating all your objects on the stack gameObject objList[100];, and each of them has a big array in them COLORREF spriteData[256][256];. That's your stack overflow.

使用 std :: vector 存储对象.

这篇关于C ++对象数组堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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