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

标签 c++ struct header-files

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

这是 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 中定义的引用?还是我的实现完全错误?提前致谢!

最佳答案

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

在 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
}

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

关于C++结构类型重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085614/

相关文章:

c++ - Dynamic_cast 共享库的问题

c++ - Qt moc.exe - 32 位和 64 位版本之间的区别?

ios - Swift 2 Dictionary<String, AnyObject> 到 Struct getter/setter throwing Cannot subscript value ... with an index of type 'String'

c++ - 从文件中读取信息

c - 为什么我需要标题?

c++ - while循环创建无限循环

c - 如何将结构链接到函数?

c++ - 如何避免仅包含 header 的库中的循环依赖关系?

C++ 泛型类——分离接口(interface)和实现

c++ - 删除数组中的尾随零