我使用以下代码在player.h文件中创建了一个名为cannon的精灵
void createPlayer() {
Texture cannonTexture;
if (!cannonTexture.loadFromFile("assets/cannon.png")) {
cout << "Failed to load cannon.png" << '\n';
}
Sprite cannon;
cannon.setTexture(cannonTexture);
cannon.setPosition(500, 500);
}
然后我在main.cpp文件中使用这段代码来调用函数并绘制精灵。
createPlayer();
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)) {
window.close();
}
}
window.clear(Color(255, 255, 255));
window.draw(cannon);
window.display();
}
但是我在“window.draw(cannon);”中的“cannon”下看到了一条红色曲线错误消息“标识符‘cannon’未定义”
所以这是基本的 C++。变量仅存在于声明它们的范围中,在这种情况下
cannon
仅存在于函数createPLayer
中,因此不允许在调用函数中使用它。
要实现此功能,您必须从创建该对象的函数中返回该对象,如下所示
Sprite createPlayer() {
Texture cannonTexture;
if (!cannonTexture.loadFromFile("assets/cannon.png")) {
cout << "Failed to load cannon.png" << '\n';
}
Sprite cannon;
cannon.setTexture(cannonTexture);
cannon.setPosition(500, 500);
return cannon;
}
然后您可以像这样在调用函数中使用返回值
Sprite cannon = createPlayer();
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == Event::Closed || Keyboard::isKeyPressed(Keyboard::Escape)) {
window.close();
}
}
window.clear(Color(255, 255, 255));
window.draw(cannon);
window.display();
}
变量作用域是 C++(以及大多数其他编程语言)中的基本概念。我不知道你是如何在没有了解的情况下走到这一步的。也许您应该从更好的来源学习 C++?