C++结构类型重定义错误

c++ struct type redefinition error

我正在使用 SFML 库开发一款简单的 C++ 游戏。这是我第一次尝试使用 C++,我 运行 遇到了一些在 header 中定义结构的问题。

这里是 bullet.h:

#pragma once
#include <SFML\Graphics.hpp>

struct BulletTransform {
    sf::RectangleShape shape;
    //details
    BulletTransform(float, float);
};

class Bullet {
//class definition stuff, no problems here

然后我尝试在 bullet.cpp 文件中创建一个实现:

#include "Bullet.h"

struct BulletTransform {

    sf::RectangleShape shape;
    BulletTransform::BulletTransform(float mX, float mY)
    {
        //constructor for shape stuff
    }
};

现在,当我尝试编译时,它抛出一个错误,指出 bullet.cpp 中的结构是类型重定义。我知道我不能两次定义同名的结构,但我也不确定如何解决这个问题。我是否需要以某种方式获得对 header 中定义的引用?还是我的实现完全错误?提前致谢!

您在实现文件中重复了结构定义。不要那样做。相反,为各个成员提供定义,如下所示:

#include "Bullet.h"


BulletTransform::BulletTransform(float mX, float mY)
{
    //constructor for shape stuff
}

在头文件中可以进行声明。在源文件中的定义——这是一般的经验法则。例如你的情况:

在bullet.h中:

struct BulletTransform {
    sf::RectangleShape shape;

    // cntr
    BulletTransform(float mX, float mY) ;

    // other methods
    void Function1(float x, float y, float z);


};

在bullet.cpp中:

BulletTransform::BulletTransform(float mX, float mY) {
  // here goes the constructor stuff
}

void BulletTransform::Function1(float x, float y, float z) {
// ... implementation details
}

通常你不会在构造函数中做一些繁重的事情——只是将数据成员初始化为一些默认值。 希望这有帮助。