我想将 Game 类分成标题和源代码。为此,我需要能够在类外部定义函数,但奇怪的是,我不能!
main.cpp
#include "app.hpp"
int main ()
{
Game game(640, 480, "Snake");
game.run();
return 0;
}
app.hpp
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class App
{
friend class Game;
public:
App(const int X, const int Y, const char* NAME);
void run(void);
private: // Variables
sf::RenderWindow window;
sf::Event event;
sf::Keyboard kboard;
};
#include "game.hpp"
现在是问题部分。
game.hpp。
class Game // this snippet works perfectly
{
public:
Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE)
{ /* and the initialization of the Game class itself... */}
void run()
{ app.run(); /* And the running process of Game class itself*/};
private:
App app;
};
class Game // this snippet produces compiler errors of multiple definitions...
{
public:
Game(const int X, const int Y, const char* TITLE);
void run();
private:
App app;
};
Game::Game(const int X, const int Y, const char* TITLE) : app(X, Y, TITLE) {}
void Game::run() { app.run(); } // <<< Multiple definitions ^^^
为什么?
最佳答案
What is the reasoning for the multiple definitions error?
因为您在头文件中定义函数,并且当您在翻译单元中包含头文件时,会在每个 translation unit 中创建该函数的拷贝,从而导致多重定义和违反 one definition rule .
What is the solution?
您可以单独定义函数,但可以在 cpp 文件中定义。您在头文件中声明函数并在源 cpp 文件中定义它们。
Why first example works?
绕过定义规则的唯一符合标准的方法是使用inline
函数。当您在类体内定义函数时,它们是隐式内联
,程序可以成功绕过一个定义规则和多个定义链接错误。
关于c++ - 不能在类外定义类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906973/