gpt4 book ai didi

c++ - 程序因对象 vector 而崩溃

转载 作者:行者123 更新时间:2023-12-03 03:12:13 28 4
gpt4 key购买 nike

我正在制作一个带有填充对象的全局 vector 的程序,并将其放入命名空间中,这是代码:

Character.h:

#include <vector>
class Character
{
//Constructor and variable declaration, etc.
}
class Player: public Character
{
//Constructor and variable declaration, etc.
}
namespace chr
{
extern std::vector<Character> characters;
extern Player player_one;
}

Character.cpp:

namespace chr
{
Player player_one("name");
std::vector <Character> characters;
}

主要:

#include <SFML/Graphics.hpp> //I'm using the SFML libraries
#include "Personaje.h"

int main()
{
Player player_two("name"); //just to test that single object work (they do)
chr::personajes.push_back(chr::player_one); //HERE'S THE ISSUE

//sample SFML code to check if the rest of the program works
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
shape.setFillColor(sf::Color::Green);

while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();

}

window.clear();
window.draw(shape);
window.display();
}

return 0;
}

当我构建此代码时(我使用的是 code::Blocks),它实际上编译时没有错误,但是当我运行它时,一旦控制台出现(SFML 窗口甚至不会弹出),它就会卡住并且出现 Windows 通知,通知我我的程序已停止工作。我知道这是 chr 命名空间 上的代码造成的,因为如果我将其注释掉,程序就可以正常运行,但我不知道这是为什么。如果有任何帮助,当程序崩溃时,Windows 打开 Visual Studio 调试器,它会生成以下消息:

Exception thrown at 0x0044EFA2 in wtfhappened.exe: 0xC0000005: Access violation reading location 0xFFFFFFFC.

If there is a handler for this exception, the program may be safely continued.

感谢您的宝贵时间

最佳答案

std::vector <Character> characters;

这是一个角色的容器。不是玩家。

chr::personajes.push_back(chr::player_one);

这将获取您的玩家,并从中创建一个新角色并放入 vector 中。玩家在角色之上拥有的所有信息都将丢失,并且您很容易遇到名为 slicing 的情况。 。我会猜测并说这不是你想要的。

有多种方法可以处理这个问题。首先,没有字符容器,而是字符引用容器(此处以简单英语含义使用,而不是 C++ 引用)。您可能需要研究智能指针(即 std::shared_ptr<> ),以尽可能轻松地实现这一点。

关于c++ - 程序因对象 vector 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38687669/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com