QA Friday 2016-Jan-01
Take Up Code - En podcast af Take Up Code: build your own computer games, apps, and robotics with podcasts and live classes
Kategorier:
How are namespaces and include files related and why do we need both? If you’re creating a class called Game and intend to use the Game class from your main method that’s in the file main.cpp then instead of putting the Game class also in the main.cpp file, create two new files, Game.h and Game.cpp. The Game.h file will declare your Game class with all its data and method declarations. It should also create a namespace. Let’s call the namespace DeltaGames after the company you plan to start with your new game. So Game.h will declare the DeltaGames namespace and then declare the Game class inside the namespace. You need to make use of strings in your Game class so you also include the standard string header from your Game.h file. But the string class is in a different std namespace. You decide to follow my guidance about not making any using namespace declaration inside your header files and instead fully qualify each and every reference to the string class with the std namespace first. You do this everywhere in the Game class in the Game.h file. Then in your Game.cpp file, the first thing you do is to include the Game.h file. This brings in the string header file along with it. But it doesn’t bring any using namespace statements. You could continue to explicitly refer to std::string in the Game.cpp file but this is the appropriate place to issue a using namespace statement so near the top of your Game.cpp file right after you include all your header files, you write: using namespace std; using namespace DeltaGames; This says that you’ll be using both the std ad DeltaGames namespaces. and you can then implement all the methods in the Game class. The only thing left is the main.cpp file. Here, you include the Game.h header file and any other header files needed. After all the header files, you also write: using namespace DeltaGames; If you need to use the std namespace, then go ahead and issue that using statement too. for this example, I’m just focusing on what you need to use the Game class. Now, you can instantiate instances of the Game class and call methods without needing to explicitly state that they all belong to the DeltaGames namespace.