首页 > 解决方案 > 如何修复 sfml c++ 代码编译错误?

问题描述

我创建了 2 个 .cpp 文件和 2 个 .header 文件

  1. main.cpp(主 .cpp 文件)
  2. main.hpp(主头文件)
  3. 游戏.cpp
  4. 游戏.hpp

我在 game.hpp 中使用了 main.hpp 组件

代码:

#include <SFML/Graphics.hpp>
#include <bits/stdc++.h>
#include "Window.hpp"
using namespace std;

class Ship{
public:
    Ship();
    ~Ship();

    int ship_x=400-28;
    int ship_y=600-55;

    sf::Texture ship_texture;
    sf::Sprite ship_sprite;

    Window *window = new Window();

    void Ship_Void(){
        if(window->event.type==sf::Event::KeyPressed){
            if(window->event.key.code==sf::Keyboard::D){
                if(ship_sprite.getPosition().x<=544)
                    ship_sprite.move(sf::Vector2f(0.04, 0));
            }
            if(window->event.key.code==sf::Keyboard::A){
                if(ship_sprite.getPosition().x>=200)
                    ship_sprite.move(sf::Vector2f(-0.04, 0));
            }
            if(window->event.key.code==sf::Keyboard::W){
                if(ship_sprite.getPosition().y>=0)
                    ship_sprite.move(sf::Vector2f(0, -0.04));
            }
            if(window->event.key.code==sf::Keyboard::S){
                if(ship_sprite.getPosition().y<=545)
                    ship_sprite.move(sf::Vector2f(0, 0.04));
            }
        }
    }

    void Keys(){
        ship_texture.loadFromFile("images/spaceship.png");
        ship_sprite.setTexture(ship_texture);
        ship_sprite.setPosition(ship_x, ship_y);
    }
};

编译命令:

g++ Window.cpp -o game -lsfml-graphics -lsfml-window -lsfml-system

编译错误:

In file included from Ship.hpp:3,
                 from Window.cpp:2:
Window.hpp:5:7: error: redefinition of ‘class Window’
5     | class Window{
      |       ^~~~~~
In file included from Window.cpp:1:
Window.hpp:5:7: note: previous definition of ‘class Window’
5 | class Window{

请帮助修复此错误!

标签: c++sfml

解决方案


放在#include "game.hpp"文件 main.cpp 的顶部


推荐阅读