簡體   English   中英

無法定義類函數OUTSIDE類

[英]Can't define class functions OUTSIDE class

我想將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 ^^^

為什么?

多重定義錯誤的原因是什么?

因為要在頭文件中定義功能,並且在轉換單元中包含頭時,會在每個轉換單元中創建該函數的副本,從而導致多個定義並違反一個定義規則

解決辦法是什么?

您可以在cpp文件中單獨定義功能。 您可以在頭文件中聲明函數,並在源cpp文件中定義它們。

為什么第一個示例有效?

繞過一個定義規則的唯一符合標准的方法是使用inline函數。 當您在類主體中定義函數時,它們是隱式inline ,程序可以成功繞過一個定義規則和多定義鏈接錯誤。

因為您要兩次定義class Game 這是您布置分隔的方法:

類.hpp

class Class
{
    public:
        Class();
        void foo();
};

類.cpp

Class::Class() { //Do some stuff}
void Class::foo() { //Do other stuff }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM