c++ - 不能在类外定义类函数

标签 c++ class layout multiple-definition-error

我想将 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/

相关文章:

c++ - 整型变量的奇数 C/C++ 初始化语法

c++ - 有没有我不会使用 std::make_shared 的情况?

Python:嵌套类而不使导入复杂化

android - TabWidget 之间的分隔符

android - 如何为我的相对布局设置 alpha 值?

c++ - 逻辑或表达式 c++

c++ - 迭代器越界并导致段错误

c++ - 一个包含 3 个对象的类,它们有指向彼此的指针,以及一个用于传递对这些对象的引用的初始化列表。错误

java - java中构造函数类型不匹配

Android自定义对话框线性布局大小与对话框背景图像相同