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

时间:2013-04-09 01:24:31

标签: c++ sfml identifier

我最近开始选择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的名称。据我搜索,并通过猜测尝试,我没有成功使绘图功能与我的精灵在另一个文件上工作。 我觉得我错过了一些大的,非常明显的(在任何一个文件上),但话又说回来,每个职业选手都曾经是个新手。

3 个答案:

答案 0 :(得分:73)

您可以使用标头文件。

良好做法。

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

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

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


int playerSprite();  // Here

int main()
{
    // ...   
    int p = playerSprite();  
    //...

答案 1 :(得分:4)

在@ user995502的答案中,关于如何运行程序的内容很小。

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

答案 2 :(得分:0)

你的精灵是在playerSprite函数的中途创建的......它也超出了范围,并且在同一个函数的末尾不再存在。必须创建一个精灵,你可以将它传递给playerSprite来初始化它,以及你可以将它传递给你的绘制函数的地方。

或许将其声明为您的第一个while