使用矢量push_back代码创建对象副本时遇到问题

having trouble creating copies of objects using vector push_back code

本文关键字:副本 创建对象 遇到 问题 代码 back push      更新时间:2023-10-16

每次按下空格键时,我都会尝试复制 RectangleShape rect1,但不是这样做,而是似乎在我释放空格键后立即删除了矢量 Vec 中的 rect1 对象。我不知道为什么,有人帮我吗?

这是我的代码:

int main() {
class shape {
public:
    RectangleShape rect1;
};
shape getShape;
getShape.rect1.setSize(Vector2f(100, 100));
getShape.rect1.setFillColor(Color(0, 255, 50, 30));
RenderWindow window(sf::VideoMode(800, 600), "SFML Game"); 
window.setFramerateLimit(60);          
window.setKeyRepeatEnabled(false);
bool play = true;
Event event;    
while (play == true) {
    while (window.pollEvent(event)) {
        if (event.type == Event::Closed) {
            play = false;
        }
    }
    window.clear();
    vector <shape> Vec;
    if (Keyboard::isKeyPressed(Keyboard::Space)) {
        Vec.push_back(getShape);
    }
    for (int i = 0; i < Vec.size(); ++i) {
        window.draw(Vec[i].rect1);
    }
    window.display();
}
window.close();
return 0;
}

你需要将向量放在循环之外,否则每次都会创建一个新的空向量:

int main() {
    // If you need to use this class in something other than main,
    // you will need to move it outside of main.
    class shape {
    public:
        RectangleShape rect1;
    };
    // But in this particular case you don't even need a class,
    // why not just use RectangleShape?
    shape getShape;
    getShape.rect1.setSize(Vector2f(100, 100));
    getShape.rect1.setFillColor(Color(0, 255, 50, 30));
    RenderWindow window(sf::VideoMode(800, 600), "SFML Game"); 
    window.setFramerateLimit(60);          
    window.setKeyRepeatEnabled(false);
    bool play = true;
    Event event;
    std::vector<shape> Vec; // Put your vector here!
    // play is already a bool, so you don't need == true
    while (play) {
        while (window.pollEvent(event)) {
            if (event.type == Event::Closed) {
                play = false;
            }
        }
        window.clear();
        if (Keyboard::isKeyPressed(Keyboard::Space)) {
            Vec.push_back(getShape);
        }
        for (int i = 0; i < Vec.size(); ++i) {
            window.draw(Vec[i].rect1);
        }
        window.display();
    }
    window.close();
    return 0;
}