我正在使用 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/