c++ - SFML - sf::RenderWindow, dividing files -
so trival need know why happen way , how can change it.
so started learn sfml today , reading sfml game development ebook , saw interesting , written code. went through tutorials sfml , started learn language understood general idea of way how should work.
so wanted remember new keywords, constructors, methods make code organized - using have learned keep clean , easy edit, debug.
my first code display window , created same code in both ways, putting main function , separated. thing first window displayed long won't close , second 1 displaying less second , program turning off.
it because destructor called right after turn on , adding more functions keep object busy way go well, want understand it. it's last thing don't understand learned objective programming. way objects working. right after create them, using them task, when done being deleted, need them again. wish understand how work , find easy , quick fix/idea make work long want to.
code :
first program:
#include <sfml/graphics.hpp> int main() { sf::renderwindow mainwindow(sf::videomode(800,600),"main window"); while(mainwindow.isopen()) { sf::event openevent; while(mainwindow.pollevent(openevent)) { switch(openevent.type) { case sf::event::closed: mainwindow.close(); break; } mainwindow.clear(); mainwindow.display(); } } } second program:
main.cpp
#include <sfml/graphics.hpp> #include "game.cpp" int main() { game game; game.run(); } game.cpp
#include "game.h" game::game() { sf::renderwindow mainwindow(sf::videomode(800,600),"main window"); } void game::run() { while(mainwindow.isopen()) { sf::event openevent; while(mainwindow.pollevent(openevent)) { switch(openevent.type) { case sf::event::closed: mainwindow.close(); break; } } mainwindow.clear(); mainwindow.display(); } } game.h
class game { public: game(); void run(); private: sf::renderwindow mainwindow; };
game::game() { sf::renderwindow mainwindow(sf::videomode(800,600),"main window"); } in constructor here, creating new renderwindow object, destroyed once constructor exits. want initialize renderwindow member of class. can in 1 of 2 ways, either using renderwindow constructor in member initializer list:
game::game() :mainwindow(sf::videomode(800,600),"main window") {} or calling create function in constructor body.
game::game() { mainwindow.create(sf::videomode(800,600),"main window); }
Comments
Post a Comment