如何调用在另一个文件中找到的函数
How to call on a function found on another file?
我最近开始学习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"
相关文章:
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 使用其他头文件函数的头文件
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 如何指定创建文件函数获取未缓存的结果?
- 标准库头文件函数原型的实现是如何用 c++ 编写的?
- 如何将类对象作为对另一个头文件函数的引用传递
- 读取文件函数lpbuffer和字节以读取澄清
- C++ - 未定义的对多个文件函数的引用
- 使用C++的可视 Unicode 文件函数
- C 创建文件函数错误
- WinAPI 创建文件函数 2.
- 具有CREATE_ALWAYS处置的创建文件函数
- 重写c库文件函数
- 如何使用客户端调用堆栈中的地址从 PDB 检索文件/函数/行号?
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- 是否可以在不使用文件函数的情况下使用代码块从文件运行某些用例测试?
- 如何用c++文件函数读写8位整数单位形式的数据
- 在c++中读文件函数如何识别文本文件的结束
- 使用Windows API的c++文件函数