如何修复 sfml c++ 代码编译错误?

How can I fix sfml c++ code compilation error?

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

  1. main.cpp(主 .cpp 文件)
  2. main.hpp(主头文件)
  3. game.cpp
  4. game.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{

请帮助修复此错误!

#include "game.hpp" 置于文件 main.cpp 之上

比方说,您想在 main.cpp 中使用一些其他变量、函数、类 或您在 中定义 的其他标识符 game.cpp

准则是将您希望在外部使用的内容的声明 放入header 文件中。

所以如果你有game.cpp的这个内容(函数有两个定义):

#include <iostream>

namespace mygame {

    void a() { 
       std::cout << "A";
    }

    int b() {
       std::cout << "B";
       return 1;
    }

}

并且您想在 main.cpp 中使用 b(),然后在 header 中添加 b 声明 ] game.hpp:

#ifndef GAME_HPP
#define GAME_HPP

int b();

#endif

然后通过将 #include "game.hpp" 放在 main.cpp 之上,将 header 包含在 main.cpp 中,这样您就可以使用 b()自由地。所以 main.cpp 可能看起来像:

#include <iostream>
#include "game.hpp"

int main()
{
   std::cout << "MAIN";
   mygame::b();
   int x = mygame::b(); // remember that b() returns int
}

请注意 game.hpp 还包含一些丑陋的命令。它们对 #include 文件本身不是必需的,但应该用于防止 多重定义 。要了解更多信息,请查找 Header Guards

另请注意,技术上您可以包含源文件 game.cpp,而不是 game.hpp,但不要这样做,因为编译器会向您显示大量令人费解的消息。不要那样做,直到你知道预处理器+编译器+链接器是如何协同工作的。