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

105

我最近开始学习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;
}

玩家.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个回答

150

您可以使用头文件。

好的实践方法。

您可以创建一个名为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();  
    //...

3
好的,你先生,你很接近拯救我的局面。我总是听说这些可恶的头文件,但从未真正研究过它们,它们相当重要,对吧?但是还有一个问题,一旦我完成了这个,并将其导入到“main.cpp”中,我的“main.cpp”文件在“window.draw”区域会是什么样子,该如何进行呢? - user1932645
1
问题,在我的player.h文件中 - "#idndef PLAYER_H" "#idndef"不是被识别的预处理设备 - 你是否意味着"#ifndef"? - user1932645
1
@dust_ 好的,我很抱歉,我完全迷失了。你能否请展示给我,或者再深入解释一下? - user1932645
3
main.cpp 如何知道要在 player.cpp 中查找代码? - Aaron Franke
1
请原谅我的基础,那么基本上 .h 文件的作用类似于 Java 中的接口吗? - A N Syafiq.
显示剩余8条评论

29

@user995502的回答中有一点需要补充,即如何运行程序。

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


-2
你可以创建一个项目,并将main.cpp和player.cpp文件包含在其中。
然后这应该在main.cpp文件中工作。
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.cpp"

3
永远不要包括源代码文件。 - Jason

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接