如何调用在另一个文件中找到的函数?

我最近开始学习 C + + 和 SFML 库,我想知道如果我在一个名为“ player.cpp”的文件上定义了一个 Sprite,我该如何在位于“ main.cpp”的主循环上调用它?

下面是我的代码(请注意,这是 SFML 2.0,而不是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

#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 的名称。到目前为止,我已经搜索,并尝试通过猜测,我没有成功地使绘图功能与我的精灵在另一个文件。 我觉得我错过了一些大的,非常明显的东西(在任何文件) ,但话说回来,每个专业人士都曾经是一个新手。

202353 次浏览

You can use header files.

Good practice.

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();
//...

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();
//...

Small addition to @user995502's answer on how to run the program.

g++ player.cpp main.cpp -o main.out && ./main.out