如何调用在另一个文件上找到的函数? [英] How to call on a function found on another file?
问题描述
我最近开始使用C ++和SFML库,我想知道我是否在适当地称为 player.cpp的文件上定义了Sprite,如何在位于 main的主循环中调用它? cpp?
I'm recently starting to pick up C++ and the SFML library, and I was wondering if I defined a Sprite on a file appropriately called "player.cpp" how would I call it on my main loop located at "main.cpp"?
这是我的代码(请注意,这是SFML 2.0,而不是1.6!)。
Here is my code (Be aware that this is SFML 2.0, not 1.6!).
main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.cpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "Skylords - Alpha v1");
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
window.draw();
window.display();
}
return 0;
}
player.cpp
player.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
int playerSprite(){
sf::Texture Texture;
if(!Texture.loadFromFile("player.png")){
return 1;
}
sf::Sprite Sprite;
Sprite.setTexture(Texture);
return 0;
}
我需要帮助的地方是 main.cpp
在我的绘图代码中显示 window.draw();
的位置。在该括号中,应该有要加载到屏幕上的Sprite的名称。据我搜索并通过猜测进行的尝试,我还没有成功地使该draw函数与我的sprite在另一个文件上一起使用。
我觉得我缺少大的东西,而且非常明显(在两个文件中都非常明显),但是每位专业人士再一次都是新手。
Where I need help is in the main.cpp
where it says window.draw();
in my draw code. In that parenthesis, there should be the name of the Sprite that I want to load onto the screen. As far as I've searched, and tried by guessing, I have not succeeded into making that draw function work with my sprite on the other file.
I feel like I'm missing something big, and very obvious (on either files), but then again, every pro was once a newb.
推荐答案
您可以使用头文件。
良好做法。
您可以创建一个名为 player.h的文件
在该头文件中声明其他cpp文件所需的所有功能,并在需要时将其包括在内。
You can create a file called player.h
declare all functions that are need by other cpp files in that header file and include it when needed.
player.h
#ifndef PLAYER_H // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H
#include "stdafx.h"
#include <SFML/Graphics.hpp>
int playerSprite();
#endif
player.cpp
#include "player.h" // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"
int playerSprite(){
sf::Texture Texture;
if(!Texture.loadFromFile("player.png")){
return 1;
}
sf::Sprite Sprite;
Sprite.setTexture(Texture);
return 0;
}
main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h" //Here. Again player.h must be in the current directory. or use relative or absolute path to it.
int main()
{
// ...
int p = playerSprite();
//...
不这样的好习惯,但适用于小型项目。在main.cpp中声明您的函数
Not such a good practice but works for small projects. declare your function in main.cpp
#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"
int playerSprite(); // Here
int main()
{
// ...
int p = playerSprite();
//...
这篇关于如何调用在另一个文件上找到的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!