87

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

这是我的代码(请注意,这是 SFML 2.0,而不是 1.6!)。

主文件

#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;
}

播放器.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 的名称。据我搜索并通过猜测尝试,我还没有成功地使该绘图功能与另一个文件上的精灵一起工作。我觉得我遗漏了一些重要的、非常明显的东西(在任何一个文件上),但话又说回来,每个专业人士都曾经是新手。

4

2 回答 2

122

您可以使用头文件。

好习惯。

您可以在该头文件中创建一个名为player.h声明其他 cpp 文件所需的所有函数的文件,并在需要时包含它。

播放器.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

播放器.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;
}

主文件

#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 中声明你的函数

#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"


int playerSprite();  // Here

int main()
{
    // ...   
    int p = playerSprite();  
    //...
于 2013-04-09T01:27:32.843 回答
26

@user995502 关于如何运行程序的答案的小补充。

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

于 2018-07-14T05:45:55.540 回答