Saf*_*ixk 60 c++ identifier sfml
我最近开始学习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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我需要帮助的main.cpp地方window.draw();在我的绘图代码中所说的位置.在该括号中,应该有我想要加载到屏幕上的Sprite的名称.据我搜索,并通过猜测尝试,我没有成功使绘图功能与我的精灵在另一个文件上工作.我觉得我错过了一些大的,非常明显的(在任何一个文件上),但是再一次,每个职业选手都曾经是一个新手.
小智 84
您可以使用头文件.
好的做法.
您可以创建一个名为player.hdeclare 的文件,声明该头文件中其他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
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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();
//...
Run Code Online (Sandbox Code Playgroud)
这不是一个好的做法,但适用于小型项目.在main.cpp中声明你的函数
#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"
int playerSprite(); // Here
int main()
{
// ...
int p = playerSprite();
//...
Run Code Online (Sandbox Code Playgroud)