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

How to call on a function found on another file?

本文关键字:文件 函数 另一个 何调用 调用      更新时间:2023-10-16

我最近开始学习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();。在括号中,应该有我想要加载到屏幕上的精灵的名称。根据我的搜索和猜测,我并没有成功地将绘制功能与另一个文件中的精灵一起工作。我觉得我错过了一些重要的,非常明显的东西(在两个文件中),但话说回来,每个专业人士都曾经是新手。

可以使用头文件。

良好实践。

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

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

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

您可以创建一个项目,并包含main.cpp和player.cpp文件。

那么这应该在main.cpp文件中工作。

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