- Game Development Patterns and Best Practices
- John P. Doran Matt Casanova
- 375字
- 2021-07-02 23:43:45
Static keyword in class definitions
The second way is by having a variable or function in a class being defined as static. Normally, when you create an instance of a class, the compiler has to set aside additional memory for each variable that is contained inside of the class in consecutive blocks of memory. When we declare something as static, instead of creating a new variable to hold data, a single variable is shared by all of the instances of the class. In addition, since it's shared by all of the copies, you don't need to have an instance of the class to call it. Take a look at the following bolded code to create our variable:
class StaticExamples
{
public:
static float classVariable;
static void StaticFunction()
{
// Note, can only use static variables and functions within
// static function
std::string toDisplay = "\n I can be called anywhere!
classVariable value: " + std::to_string(classVariable);
printf(toDisplay.c_str());
}
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, in the preceding code we define a variable and a function, but this isn't all the prep work we need to do. When creating a static variable, you cannot initialize it from within the class, and instead need to do it in a .cpp file instead of the .h file we could use for the class definition. You'll get errors if you do not initialize it, so it's a good idea to do that. In our case, it'd look like the following:
// StaticExamples.cpp
float StaticExamples::classVariable = 2.5f;
Note that, when we initialize, we also need to include the type, but we use the ClassName::variableName template similar to how you define functions in .cpp files. Now that everything's set up, let's see how we can access them inside our normal code:
StaticExamples::StaticFunction();
StaticExamples::classVariable = 5;
StaticExamples::StaticFunction();
Note that instead of accessing it via creating a variable, we can instead just use the class name followed by the scope operator (::) and then select which static variable or function we'd like to use. When we run it, it'll look like this:

As you can see, it works perfectly!
- 軟件項目估算
- SQL Server 2012數據庫技術及應用(微課版·第5版)
- MongoDB for Java Developers
- Java Web及其框架技術
- Cassandra Data Modeling and Analysis
- Scala for Machine Learning(Second Edition)
- 基于SpringBoot實現:Java分布式中間件開發入門與實戰
- 運維前線:一線運維專家的運維方法、技巧與實踐
- 3ds Max印象 電視欄目包裝動畫與特效制作
- JavaScript程序設計:基礎·PHP·XML
- HTML+CSS+JavaScript網頁制作:從入門到精通(第4版)
- 零基礎學C++(升級版)
- LabVIEW數據采集
- Android編程權威指南(第4版)
- 關系數據庫與SQL Server 2012(第3版)