【发布时间】:2021-04-04 05:19:30
【问题描述】:
我有一个标题,它定义了我需要的一些功能。我将它们包含在两个文件中,这些文件本身包含在 main.cpp 中,但是我得到了函数错误的多个定义,尽管我放了
#ifndef MYFUNCTION_H
#define MYFUNCTION_H
//code
#endif
在我的代码中。 那么我做错了什么?这是我的标题:
#ifndef EXTRASFMLFUNCTIONS_H
#define EXTRASFMLFUNCTIONS_H
#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Text.hpp>
inline void setCenterPos(sf::Sprite &entity, const sf::Vector2f& position)
{
entity.setPosition(sf::Vector2f{(position.x - entity.getGlobalBounds().width / 2), position.y - (entity.getGlobalBounds().height / 2)});
}
inline void setCenterPos(sf::Text &entity, const sf::Vector2f& position)
{
entity.setPosition(sf::Vector2f{(position.x - entity.getGlobalBounds().width / 2), position.y - (entity.getGlobalBounds().height / 2)});
}
inline sf::Vector2f getCenter(const sf::Sprite& entity)
{
return sf::Vector2f{entity.getGlobalBounds().width / 2, entity.getGlobalBounds().height / 2} + entity.getPosition();
}
inline void scaleTo(sf::Sprite& entity, const sf::Vector2f& size)
{
entity.scale(size.x / entity.getGlobalBounds().width, size.y / entity.getGlobalBounds().height);
return;
}
inline void scaleToWidth(sf::Sprite& entity, const float &width)
{
entity.scale(width / entity.getGlobalBounds().width, width / entity.getGlobalBounds().width);
return;
}
inline void scaleToHeight(sf::Sprite& entity, const float &height)
{
entity.scale(height / entity.getGlobalBounds().height, height / entity.getGlobalBounds().height);
return;
}
#endif
编辑:它与 inline 关键字一起使用
【问题讨论】:
-
重要提示:标题保护,
ifndef的东西,防止在单个 translation unit 中包含多个内容。一个 cpp 文件不会多次在标头中包含这些内容。两个 cpp 文件可以每个包含一次标头,当链接在一起时,可能会出现多个定义。 -
该标题中的所有内容都是
inline,这应该可以解决任何多个定义问题。你正在做一些奇怪的事情,你的问题没有很好地解释。请使用minimal reproducible example 更新问题。我们可以用来重现问题。 -
我复制粘贴错了,抱歉,有些函数应该有类型
-
使用
static inline而不仅仅是inline
标签: c++ function compiler-errors definition