使用矢量push_back代码创建对象副本时遇到问题
having trouble creating copies of objects using vector push_back code
每次按下空格键时,我都会尝试复制 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;
}
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- C++ 在其自己的类中创建对象的修改副本
- 使用矢量push_back代码创建对象副本时遇到问题
- 创建对象的副本以进行多重比较是一种很好的做法
- 正在创建对象的副本
- 解释器在跟踪中创建对象的副本
- 在 c++ 中创建对象的副本
- 我的代码是在创建对象的深层副本还是浅层副本
- c++:创建对象的本地副本