![](/img/trans.png)
[英]Why can't I define a object of class(which inherited another class) outside the main function?
[英]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 ^^^
為什么?
因為您要兩次定義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.