- Game Development Patterns and Best Practices
- John P. Doran Matt Casanova
- 235字
- 2021-07-02 23:43:45
Static keyword inside a function
The first one, being used inside of a function, basically means that once the variable has been initialized, it will stay in the computer's memory until the end of the program, keeping the value that it has through multiple runs of the function. A simple example would be something like this:
#include <string>
class StaticExamples
{
public:
void InFunction()
{
static int enemyCount = 0;
// Increase the value of enemyCount
enemyCount += 10;
std::string toDisplay = "\n Value of enemyCount: " +
std::to_string(enemyCount);
printf(toDisplay.c_str());
}
};
Now if we were to call this, it would look something like the following:
StaticExamples se;
se.InFunction();
se.InFunction();
And when we call it, the following would be displayed:

As you can see, the value continues to exist, and we can access and/or modify its contents as we see fit in the function. This could be used for a number of things, such as maybe needing to know what happened the last time that you called this function, or to store any kind of data between any calls. It's also worth noting that static variables are shared by all instances of the class, and due to that, if we had two variables of type StaticExamples, they would both display the same enemyCount. We will utilize the fact that, if an object is created this way, it will always be available later on in this chapter.
- 極簡算法史:從數(shù)學到機器的故事
- Docker and Kubernetes for Java Developers
- 深入淺出Java虛擬機:JVM原理與實戰(zhàn)
- arc42 by Example
- Learning ASP.NET Core 2.0
- Java程序員面試算法寶典
- Python數(shù)據(jù)分析(第2版)
- 可解釋機器學習:模型、方法與實踐
- 編程數(shù)學
- Service Mesh實戰(zhàn):基于Linkerd和Kubernetes的微服務實踐
- Android編程權(quán)威指南(第4版)
- Python數(shù)據(jù)可視化之matplotlib實踐
- Python面向?qū)ο缶幊蹋ǖ?版)
- Game Programming using Qt 5 Beginner's Guide
- Visual C++程序開發(fā)范例寶典