无法定义类函数OUTSIDE类

Mar*_*kas 1 c++ layout class multiple-definition-error

我想将Game类分为标题和源代码.要做到这一点,我需要能够在类外定义函数,但奇怪的是,我不能!

main.cpp中

#include "app.hpp"
int main ()
{
    Game game(640, 480, "Snake");
    game.run();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

现在问题部分.

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;
};
Run Code Online (Sandbox Code Playgroud)


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 ^^^
Run Code Online (Sandbox Code Playgroud)

为什么?

Alo*_*ave 7

多重定义错误的原因是什么?

因为您正在定义头文件中的函数,并且当您在翻译单元中包含标题时,会在每个翻译单元中创建该函数的副本,从而导致多个定义并违反一个定义规则.

解决办法是什么?

您可以单独定义函数,但在cpp文件中.您在头文件中声明函数并在源cpp文件中定义它们.

为什么第一个例子有效

绕过一个定义规则的唯一标准兼容方法是使用inline函数.当您在类体内定义函数时,它们是隐式的inline,程序可以成功绕过一个定义规则和多个定义链接错误.